Hacker News new | ask | show | jobs
by dakom 2726 days ago
> every single Rust crate I have used so far its creating its own `Error` enum which makes it really hard to compose `Result`.

Is there a reason why `map_err()` doesn't achieve what you need - i.e. to get everything into your error type no matter where it came from?

For example: OtherLibResult.map_err(|e| MyError::from(e))

Unless I'm mistaken - you ultimately are doing something like this in one form or another, because if you never match on the different Error variants that happened somewhere along the pipeline- then those details are being swallowed.

Implementing a From trait at least forces you to make that choice (all in one place too)- and then you can keep composing the results as needed since it's all in your MyError type

1 comments

Yes thats the pattern I ended up using with the help of `custom_error` crate which automates the implementation of `From` for your custom errors. I guess the disconnect for me was that in Java/Scala all custom exceptions extend `Throwable` so types always line up, in rust custom Errors are disjointed so you have to wrap everything yourself to align the types.
`Throwable` in Rust is `dyn std::error::Error`.

If you make your functions return `Box<dyn Error>` (or `failure::Error`), they will all convert out of the box. The `?` operator performs conversion itself. For chains `.map_err(From::from)` does it.