macro_rules! ensure { ($cond:expr, $($key:ident = $value:expr,)* $fmt:literal $($arg:tt)*) => { ... }; ($cond:expr, $err:expr $(,)?) => { ... }; }
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
ensure!(user == 0, "only user 0 is allowed");
#[derive(Error, Debug)]
enum ScienceError {
#[error("recursion limit exceeded")]
RecursionLimitExceeded,
...
}
ensure!(depth <= MAX_DEPTH, ScienceError::RecursionLimitExceeded);
use miette::{ensure, Result, Severity};
fn divide(x: f64, y: f64) -> Result<f64> {
ensure!(
y.abs() >= 1e-3,
severity = Severity::Warning,
"dividing by value ({}) close to 0", y
);
Ok(x / y)
}