macro_rules! ensure {
($cond:expr, $($err:tt)+) => { ... };
}Expand description
Ensures $cond is met; otherwise return an error.
Shorthand for if !$cond { bail!(...); }.
Accepts the same error expressions, format arguments, and message builder chains as bail!.
The condition is evaluated once; error, format, and builder arguments are evaluated only on failure.
ยงExamples
use std::error::Error;
use std::fmt;
use gix_error::ensure;
#[derive(Debug)]
struct PermissionDenied(User, Resource);
impl fmt::Display for PermissionDenied {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(fmt, "permission denied")
}
}
impl Error for PermissionDenied {}
ensure!(
has_permission(&user, &resource),
PermissionDenied(user, resource),
);Format a classified failure and attach metadata:
use gix_error::{ensure, ExnMessageResult, MetadataValue, Result};
fn captured(count: usize) -> Result {
ensure!(count > 0, "Count must be positive, got {count}".validation().with_input(count));
Ok(())
}
fn explicit(count: usize) -> ExnMessageResult {
ensure!(count > 0, "Count must be positive, got {}".validation().with_input(count), count);
Ok(())
}
captured(1)?;
let error = captured(0).expect_err("zero violates the input constraint");
assert!(error.is_validation());
assert_eq!(error.metadata().next().expect("input details")["input"], MetadataValue::U64(0));
let error = explicit(0).expect_err("zero violates the input constraint");
assert_eq!(error.error().message, "Count must be positive, got 0");
assert!(error.is_validation());