ensure

Macro ensure 

Source
macro_rules! ensure {
    (cond = $cond:expr, else = $err:expr $(,)?) => { ... };
    ($cond:expr, $err:expr $(,)?) => { ... };
}
Expand description

Abort the enclosing function with an error when a condition fails.

The macro takes either a bare condition and error expression, or the more explicit cond = ..., else = ... form. The error expression is evaluated lazily only when the condition is false.

ยงExamples

Short-circuit a typed error:

use masterror::{AppError, AppErrorKind, AppResult};

fn require(flag: bool) -> AppResult<()> {
    masterror::ensure!(flag, AppError::bad_request("flag required"));
    Ok(())
}

assert!(matches!(
    require(false).unwrap_err().kind,
    AppErrorKind::BadRequest
));

Use the verbose syntax for clarity in complex conditions:

use masterror::{AppError, AppResult};

fn bounded(value: i32, max: i32) -> AppResult<()> {
    masterror::ensure!(
        cond = value <= max,
        else = AppError::service("value too large")
    );
    Ok(())
}

assert!(bounded(2, 3).is_ok());
assert!(bounded(5, 3).is_err());