• gabmus@retrolemmy.com
    link
    fedilink
    arrow-up
    0
    ·
    edit-2
    3 months ago

    Depending on a usecase you might find that many of your “entrypoint functions” might all share the same error type. For example, if you’re making an API backend it’s likely gonna be something a status code and a message.

    In that case a simple way to avoid having to pattern match every single error is to implement From<DownstreamErrorType> for MyErrorEnum, and just use the ? operator. Example:

    fn do_something_with_database() -> Result<Whatever, DatabaseError> { /* ... */ }
    
    impl From<DatabaseError> for MyErrorType { /* ... */ }
    
    // this would be your function
    fn api_get_something() -> Result<SomeOtherType, MyErrorType> {
        let data: Whatever = do_something_with_database()?;
        // ...
        Ok(/* ... */)
    }
    

    EDIT: this is mentioned in the article already

    • treadful@lemmy.zip
      link
      fedilink
      English
      arrow-up
      0
      ·
      3 months ago

      It’s a little verbose (like most of Rust), but I really like this approach. It’ll make a lot of logic easier to reason about. I missed that in the article, so thanks for pointing it out.

      • ISO@lemmy.zip
        link
        fedilink
        arrow-up
        0
        ·
        3 months ago

        (Didn’t read the article.)

        It’s not a secret approach or anything. thiserror gives you that with a simple #[from] attribute annotation on the relevant error variant on your Error enum (which is what your Error type should be).

        In your case, this just works because you’re not attaching custom context to your error. Usually, you would want to attach some context, and in that case, .map_err()would obviously still be needed, and that’s fine. This idea of having to write as little code as possible is stupid.

        Sometimes, attaching context once is sufficient, sometimes it’s not. If it’s the former, then you can still do From in your bigger error enums which have variants from your smaller error enums (e.g. crate-level Error type with variants trivially wrapping module-level Error types).

        • treadful@lemmy.zip
          link
          fedilink
          English
          arrow-up
          0
          ·
          3 months ago

          This idea of having to write as little code as possible is stupid.

          Is it? Not only is it less work, but generally makes the code way easier to reason about. In this case, instead of just seeing simple function calls explaining the logic flow, you visually have to parse all this weird extra cruft that is generally irrelevant to what the block is doing.