---
source: https://iinventedlight.com/library/notes/rust-anyhow.md
title: "anyhow::Result with ? and .context() gives easy error handling in Rust applications"
license: CC-BY-4.0
license_url: https://creativecommons.org/licenses/by/4.0/
source_license: "MIT OR Apache-2.0 (docs.rs); MIT OR Apache-2.0 (dtolnay/anyhow (GitHub)); prose restates cited source lines in own words"
license_family: mixed-green
attribution: "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."
author: "iinventedlight (synthesis of cited sources); text drafted with AI assistance"
date: 2026-11-18
status: published
approved_by: "Cole Withington, 2026-11-20 13:14 PT: \"Publish the full batch and rewrite the 6 live notes\""
checked_on: 2026-11-18
as_of: 2026-11-18
confidence: medium
untested: "Not reproduced (2026-11-18). Official docs and source files were read; no test suite, server, or API call was run for this note."
category: coding-references
topic_area: "code-systems: anyhow errors"
tags: [rust, anyhow, error-handling, context, bail, result]
client: Librarian
sources:
  - id: S1
    title: "Crate anyhow"
    publisher: docs.rs
    url: https://docs.rs/anyhow/latest/anyhow/
    accessed: 2026-11-18
    license: "MIT OR Apache-2.0"
  - id: S2
    title: "README"
    publisher: dtolnay/anyhow (GitHub)
    url: https://github.com/dtolnay/anyhow
    accessed: 2026-11-18
    license: "MIT OR Apache-2.0"
---
# 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

```rust
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:
```text
Error: Failed to read instrs from ./path/to/instrs.json

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

## Key points

- `anyhow::Error` is a trait object based error type; `?` works for any error that implements the `std::error::Error` trait.
- Without more context about what higher level step the application was in, an error like "No such file or directory" can be annoying to debug.
- Downcasting is supported by value, by shared reference, or by mutable reference, for example `downcast_ref::<DataStoreError>()`.
- On Rust 1.65 or newer, a backtrace is captured if the underlying error type does not already provide its own. Set `RUST_BACKTRACE=1` for panics and errors, or `RUST_LIB_BACKTRACE=1` for only errors.
- In no_std mode, disable the default "std" feature; a global allocator is required.

## 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

- [rust-thiserror](https://iinventedlight.com/library/notes/rust-thiserror/)
- [rust-error-handling-result](https://iinventedlight.com/library/notes/rust-error-handling-result/)
- [rust-traits](https://iinventedlight.com/library/notes/rust-traits/)

## Claims

- id: C1
  claim: anyhow::Error is a trait object based error type.
  source: S1
  evidence: "a trait object based error type for easy idiomatic error handling"

- id: C2
  claim: bail! is shorthand for an early return.
  source: S2
  evidence: "A `bail!` macro is provided as a shorthand for the same early return."

- id: C3
  claim: Anyhow suits application code.
  source: S2
  evidence: "This is common in application code."

## Sources

- [S1] Crate anyhow. docs.rs. https://docs.rs/anyhow/latest/anyhow/ . License: MIT OR Apache-2.0. Accessed 2026-11-18.

- [S2] README. dtolnay/anyhow (GitHub). https://github.com/dtolnay/anyhow . License: MIT OR Apache-2.0. Accessed 2026-11-18.

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.

---

Agents: [/agents.md](/agents.md) | [/.well-known/agent-library.json](/.well-known/agent-library.json).
