← All notes

anyhow::Result with ? and .context() gives easy error handling in Rust applications

Answer: Use anyhow::Result<T> as the return type of any fallible function, propagate errors with ?, and attach context with .context("...") or .with_context(|| ...). Build one-off errors with anyhow! and return early with bail!.

Example

use anyhow::{anyhow, bail, Context, Result};

fn get_cluster_info() -> Result<ClusterMap> {
    let config = std::fs::read_to_string("cluster.json")
        .context("Failed to read cluster.json")?;
    let map: ClusterMap = serde_json::from_str(&config)?;
    if map.is_empty() {
        bail!("Missing attribute: {}", "nodes");
    }
    Ok(map)
}

Error with context:

Error: Failed to read instrs from ./path/to/instrs.json

Caused by:
    No such file or directory (os error 2)

Key points

anyhow or thiserror

Use Anyhow if you don't care what error type your functions return, which is common in application code. Use thiserror in a library that wants dedicated error types.

See also

Claims

Sources

License: this note is CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/). Summary by iinventedlight (AI-assisted). Sources: docs.rs, Crate anyhow; dtolnay/anyhow (GitHub), README. MIT OR Apache-2.0 (https://raw.githubusercontent.com/dtolnay/anyhow/master/LICENSE-APACHE). Copyright David Tolnay. Text was condensed and changed from the originals.

License: CC-BY-4.0 · Summary by iinventedlight (AI-assisted). Sources: docs.rs, Crate anyhow; dtolnay/anyhow (GitHub), README. MIT OR Apache-2.0 (https://raw.githubusercontent.com/dtolnay/anyhow/master/LICENSE-APACHE). Copyright David Tolnay.

Cite this

Permanent ID: iil:note:wx0jhcs6

iinventedlight. 2026. "anyhow::Result with ? and .context() gives easy error handling in Rust applications." iinventedlight Library, iil:note:wx0jhcs6, version of 2026-11-18. https://iinventedlight.com/library/notes/rust-anyhow/. License: CC-BY-4.0.

@misc{iil_note_wx0jhcs6,
  author = {{iinventedlight}},
  title = {{anyhow::Result with ? and .context() gives easy error handling in Rust applications}},
  howpublished = {iinventedlight Library},
  year = {2026},
  date = {2026-11-18},
  url = {https://iinventedlight.com/library/notes/rust-anyhow/},
  note = {Permanent ID iil:note:wx0jhcs6. License: CC-BY-4.0.},
}

Markdown

Spotted a mistake? Use the MCP feedback tool or email hello@iinventedlight.com. Or Report a correction (no account needed).

For language models and agents: start at /llms.txt | /agents.md | /.well-known/agent-library.json. This page in Markdown: /library/notes/rust-anyhow.md.