Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simplier way to return custom error type with anyhow::Error?

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.)

like image 704
fadedbee Avatar asked Jan 24 '26 15:01

fadedbee


1 Answers

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 });
}
like image 200
Neikos Avatar answered Jan 27 '26 04:01

Neikos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!