anyhow::Error
RustERRORNotableError Handling

Anyhow dynamic error with context

Quick Answer

Use anyhow in application code for ergonomic error propagation with context; use thiserror for library error types.

What this means

A dynamic error type from the anyhow crate that wraps any std::error::Error and supports adding human-readable context via .context().

Why it happens
  1. 1Any underlying error wrapped with anyhow::Context::context()
  2. 2anyhow::anyhow!() macro for ad-hoc errors

Fix

Add context to errors

Add context to errors
use anyhow::{Context, Result};
use std::fs;

fn load_config(path: &str) -> Result<String> {
    fs::read_to_string(path)
        .with_context(|| format!("failed to read config from {}", path))
}

Why this works

with_context() lazily adds a human-readable layer on top of the underlying error.

Code examples
Ad-hoc errorrust
use anyhow::anyhow;
return Err(anyhow!("value {} is invalid", x));
Sources

Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev

← All Rust errors