Macro rubbl_core::ctry
source · macro_rules! ctry {
($op:expr ; $( $chain_fmt_args:expr ),*) => { ... };
}
Expand description
A “contextualized try” macro.
This macro is syntactic sugar. The expression
ctry!(op; "spec: {}", value)
is equivalent to:
{
use anyhow::Context;
op.with_context(|| format!("spec: {}", value))?
}
So, it attempts an operation that returns a Result
(or Option
) and
evaluates to its Ok
(or Some
) value if the operation is successful.
If not, it exits the current function with an Err
value that has a
formatted context string attached to it.
Example
use rubbl_core::ctry;
use std::{fs::File, io::Write};
let path = "myfile.txt";
let mut myfile = ctry!(File::open(path); "failed to open file `{}`", path);
ctry!(write!(myfile, "hello"); "failed to write to file `{}`", path);