error-concept

anyhow::Context: describe the failed operation

Attach a short description of the operation to an error. The original cause remains available for diagnostics. A successful result keeps its value. Requires anyhow = "=1.0.104" in Cargo.toml. See the staged dependency project. Expected stdout (not executed): read item count Expected stderr: (empty) Expected exit: success Common mistake: Using context containing credentials or raw sensitive inputs.

Formal Syntax & Structure

rust syntaxrust
result.context(message)?

Working Example

Example Snippetrust
use anyhow::Context;fn main() {    let result = "bad".parse::<u32>().context("read item count");    if let Err(error) = result { println!("{error}"); }}
Rust Reference