macro_rules! ensure {
    ($expr:expr) => { ... };
    ($expr:expr, $msg:expr) => { ... };
}
Expand description

Asserts that a boolean expression is true at runtime, returning a stackable error otherwise.

Has return Err(...) with a stacked_errors::Error and attached location if the expression is false. An custom message can be attached that is used as a StackableErr argument.

use stacked_errors::{ensure, Result, StackableErr};

fn ex(val0: bool, val1: bool) -> Result<()> {
    ensure!(true);

    ensure!(val0);

    ensure!(val1, format!("val1 was {}", val1));

    Ok(())
}

ex(true, true).unwrap();

assert_eq!(
    format!("{}", ex(false, true).unwrap_err()),
    r#"Error { stack: [
Location { file: "src/ensure.rs", line: 10, col: 5 },
ensure(val0) -> assertion failed
] }"#
);

assert_eq!(
    format!("{}", ex(true, false).unwrap_err()),
    r#"Error { stack: [
Location { file: "src/ensure.rs", line: 12, col: 5 },
val1 was false
] }"#
);