ensure_eq

Macro ensure_eq 

Source
macro_rules! ensure_eq {
    ($lhs:expr, $rhs:expr) => { ... };
    ($lhs:expr, $rhs:expr, $msg:expr) => { ... };
}
Expand description

Asserts that two expressions are equal to each other (with PartialEq), returning a stackable error if they are equal. Debug is also required if there is no custom message.

Has return Err(...) with a stacked_errors::Error and attached location if the expressions are unequal. A custom message can be attached that is used as an Error::from_err argument.

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

fn ex(val0: u8, val1: &str) -> Result<()> {
    ensure_eq!(42, 42);

    ensure_eq!(8, val0);

    ensure_eq!("test", val1, format!("val1 was \"{}\"", val1));

    Ok(())
}

ex(8, "test").unwrap();

assert_eq!(
    format!("{}", ex(0, "test").unwrap_err()),
    r#"
    ensure_eq(
 lhs: 8
 rhs: 0
) -> equality assertion failed at src/macros.rs 10:5"#
);

assert_eq!(
    format!("{}", ex(8, "other").unwrap_err()),
    r#"
    val1 was "other" at src/macros.rs 12:5"#
);