Is there a macro to convert errors to panic?

Is there a macro that converts an error into a panic, like a macro try? Do I need to define my own?

For example, I would like to panic if the unit test cannot open the file. My current workaround is this:

macro_rules! tryfail {
    ($expr:expr) => (match $expr {
        result::Result::Ok(val) => val,
        result::Result::Err(_) => panic!(stringify!($expr))
    })
}

#[test]
fn foo() {
    let c = tryfail!(File::open(...));
}
+4
source share
1 answer

This is exactly what the methods do Result::unwrapand Result::expect.

I know that you are requesting a macro, but I think your use case can be done using a method unwrap:

#[test]
fn foo() {
    let c = File::open(...).unwrap();
    // vs
    let c = tryfail!(File::open(...));
}

Note that in code that is not a test, more idiomatic is used expect.

, unwrap.

+6

All Articles