error-concept

anyhow: bail! and ensure!

Return Err from the enclosing fallible function with bail!, or require a condition with ensure!. These are application error paths, not assertions that panic. Requires anyhow = "=1.0.104" in Cargo.toml. See the staged dependency project. Expected stdout (not executed): 0: false 2: true 11: false Expected stderr: (empty) Expected exit: success Common mistake: Using ensure! in a function whose return type cannot accept the error.

Formal Syntax & Structure

rust syntaxrust
anyhow::bail!(message); anyhow::ensure!(condition, message);

Working Example

Example Snippetrust
fn check(n: u32) -> anyhow::Result<u32> {    anyhow::ensure!(n > 0, "quantity must be positive");    if n > 10 { anyhow::bail!("quantity too large"); }    Ok(n)}fn main() {    for n in [0, 2, 11] { println!("{n}: {}", check(n).is_ok()); }}
Rust Reference