macro_rules! ensure {
($cond:expr, $msg:literal) => { ... };
($cond:expr, $msg:literal?) => { ... };
($cond:expr, $fmt:literal, $($arg:tt)*) => { ... };
($cond:expr, $fmt:literal, $($arg:tt)*?) => { ... };
}Expand description
Return early with an error if a condition is not satisfied.
This macro is equivalent to if !$cond { return Err(From::from($err)); }.
Analogously to assert!, ensure! takes a condition and exits the function
if the condition fails. Unlike assert!, ensure! returns an Error
rather than panicking.
ยงExample
use adhocerr::ensure;
fn main() -> Result<(), impl std::error::Error + 'static> {
ensure!(user == 0, "only user 0 is allowed");
Ok(())
}use adhocerr::ensure;
fn main() -> Result<(), anyhow::Error> {
ensure!(depth <= MAX_DEPTH, "Recursion limit exceeded"?);
Ok(())
}