|
|
|
|
|
by martijnarts
1311 days ago
|
|
For anyone interested in what this would look like in Rust now, there's two ways. For libraries, people tend to recommend the thiserror crate. Code sample[0]: #[derive(thiserror::Error, Debug)]
enum Error {
#[error("One")]
One(#[from] Error1),
#[error("Two")]
Two(#[from] Error2),
}
fn foo(r1: Result<i32, Error1>, r2: Result<i32, Error2>) -> Result<..., Error> {
let i1 = r1?;
let i2 = r2?;
// ...
}
Whereas for binaries, people usually recommend anyhow. Code sample[1]: fn foo(r1: Result<i32, Error1>, r2: Result<i32, Error2>) -> anyhow::Result<...> {
let i1 = r1?;
let i2 = r2?;
// ...
}
[0]: https://play.rust-lang.org/?version=stable&mode=debug&editio...
[1]: https://play.rust-lang.org/?version=stable&mode=debug&editio... |
|
The pattern I use in my app is to use thiserror, and then just have an anyhow catch-all. That lets me do specific stuff where I know I'm going to need specific handling, and an easy-to-use fallback for just saying "this bad thing happened" with the anyhow! macro.
I don't know if this is the best pattern but it's worked really well for me.