Using anyhow::ensure!()

(Jin Qing’s Column, Dec., 2023)

From: https://yukinarit.hashnode.dev/10-tips-of-rust-anyhow

use anyhow::{Result, bail};

fn validate(s: &str) -> Result<()> {
    if s.len() >= 10 {
        bail!("Length of string \"{}\" must be less than 10", s);
    }
    ...
}

can be rewritten as:

use anyhow::{Result, ensure};

fn validate(s: &str) -> Result<()> {
    ensure!(s.len() >= 10, "Length of string \"{}\" must be less than 10", s);
    ...
}

The example from the doc:

#[derive(Error, Debug)]
enum ScienceError {
    #[error("recursion limit exceeded")]
    RecursionLimitExceeded,
    ...
}

ensure!(depth <= MAX_DEPTH, ScienceError::RecursionLimitExceeded);

The ensure!() returns Err(anyhow!(…)) if the condition is not met.