Macro ensure

macro_rules! ensure {
    ($cond:expr $(,)?) => { ... };
    ($cond:expr, $msg:literal $(,)?) => { ... };
    ($cond:expr, $err:expr $(,)?) => { ... };
    ($cond:expr, $fmt:expr, $($arg:tt)*) => { ... };
}

Return early with an error if a condition is not satisfied.

This macro is equivalent to if !$cond { return Err(anyhow!($args...)); }.

The surrounding function's or closure's return value is required to be Result<_, [anyhow::Error][crate::Error]>.

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

# use anyhow::{ensure, Result};
#
# fn main() -> Result<()> {
#     let user = 0;
#
ensure!(user == 0, "only user 0 is allowed");
#     Ok(())
# }
# use anyhow::{ensure, Result};
# use thiserror::Error;
#
# const MAX_DEPTH: usize = 1;
#
#[derive(Error, Debug)]
enum ScienceError {
    #[error("recursion limit exceeded")]
    RecursionLimitExceeded,
    # #[error("...")]
    # More = (stringify! {
    ...
    # }, 1).1,
}

# fn main() -> Result<()> {
#     let depth = 0;
#
ensure!(depth <= MAX_DEPTH, ScienceError::RecursionLimitExceeded);
#     Ok(())
# }