I have working code which returns errors in the following way:
fn foo() -> anyhow::Result<()> {
...
Err(anyhow::Error::new(
MyError::MyVariant {
actual: 0,
expected: 1
}
))
}
Is there a more concise way of returning an instance of MyError?
(Omitting the anyhow::Error::new( wrapper causes a type-checking error, as MyError is not an instance of anyhow::Error.)
You can use the anyhow::bail! macro. It has exactly your usecase in mind:
use anyhow::bail;
fn foo() -> anyhow::Result<()> {
if errored {
bail!(MyError::MyVariant { actual: 0, expected: 1 })
}
}
As Filipe correctly points in the comments, if you find yourself checking simple conditions and returning an error you can simplify this step by using anyhow::ensure! which is quite similar to assert! but returns instead of panicing.
use anyhow::ensure;
fn foo() -> anyhow::Result<()> {
ensure!(!errored, MyError::MyVariant { actual: 0, expected: 1 });
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With