Skip to main content

match_res

Macro match_res 

Source
macro_rules! match_res {
    (
        $expr:expr
        $(, Ok($ok:pat) => $ok_handler:expr)*
        $(, Err(type<$err_ty:ty>($err:pat)) => $err_handler:expr)*
        $(,)?
    ) => { ... };
    (
        $expr:expr
        $(, Ok($ok:pat) => $ok_handler:expr)*
        $(, Err(type<$err_ty:ty>($err:pat)) => $err_handler:expr)*
        , Err(else($default_err:pat)) => $default_handler:expr
        $(,)?
    ) => { ... };
}
Expand description

Match an eyre::Result against multiple Ok patterns and multiple error types and patterns.

If no error pattern matches, propagate the error up.

ยงExample

use agglayer_errors::match_res;
use eyre::Context as _;

#[derive(Debug, thiserror::Error)]
#[error("Foo")]
struct Foo;

#[derive(Debug, thiserror::Error)]
#[error("Bar")]
struct Bar(&'static str);

fn main() -> eyre::Result<()> {
    let res: eyre::Result<u32> = Err(Bar("foo").into());
    let s = match_res!(res,
        Ok(42) => "the answer".to_string(),
        Ok(n) => format!("ok({n})"),
        Err(type<Bar>(Bar("foo"))) => "bar/foo".to_string(),
        Err(type<Bar>(b)) => format!("bar({})", b.0),
        // By default, propagate the error up
    );

    let res2: eyre::Result<u32> = Err(Foo.into());
    let s2 = match_res!(res2,
        Ok(42) => "the answer".to_string(),
        Ok(n) => format!("ok({n})"),
        Err(type<Bar>(Bar("foo"))) => "bar/foo".to_string(),
        Err(type<Bar>(b)) => format!("bar({})", b.0),
        Err(else(err)) => format!("other({err})"), // Catch-all, do not propagate
    );

    Ok(())
}