Introduction
The anyhow crate provides convenient error handling with context chains that attach descriptive messages to errors. However, when the context chain is not properly displayed or when context() is misused, critical debugging information is lost. In production, error logs that show only the innermost error without context make incident response significantly harder. Understanding the difference between context(), wrap(), and the Display/Debug implementations is essential for effective error reporting.
Symptoms
- Error log shows only innermost error without context messages
format!("{:?}", err)shows full chain butformat!("{}", err)shows only top messagecontext()called onOkvalue unnecessarily, adding overhead- Context messages not including variable values for debugging
- Error chain broken by
map_errinstead ofcontext
Debug error chain: ```rust use anyhow::Context;
fn process() -> anyhow::Result<()> { let config = std::fs::read_to_string("config.toml") .context("Failed to read config file")?;
let data: Config = toml::from_str(&config) .context("Failed to parse config as TOML")?;
Ok(()) }
// When this fails, the error chain is: // "Failed to parse config as TOML" // "Failed to read config file" // "No such file or directory (os error 2)" ```
Common Causes
- Using
map_err(|e| anyhow!(e))instead ofcontext()which loses the chain - Only logging
err.to_string()instead of full debug format - Context messages too generic to be useful for debugging
wrap_errvscontextconfusion for non- anyhow errors- Error chain truncated by
.into()conversion
Step-by-Step Fix
- 1.Use context() to add descriptive messages without losing the chain:
- 2.```rust
- 3.use anyhow::{Context, Result};
fn load_database(url: &str) -> Result<Database> { // CORRECT - context preserves the original error AND adds message let conn = tokio_postgres::connect(url, NoTls) .await .with_context(|| format!("Failed to connect to database: {}", url))?;
Ok(Database::new(conn)) }
// WRONG - map_err loses the original error chain fn load_database_wrong(url: &str) -> Result<Database> { let conn = tokio_postgres::connect(url, NoTls) .await .map_err(|e| anyhow::anyhow!("Failed to connect: {}", e))?; // Original error details lost - only the stringified version remains
Ok(Database::new(conn)) } ```
- 1.**Log full error chain in production":
- 2.```rust
- 3.use anyhow::Context;
fn handle_error(err: anyhow::Error) { // WRONG - only shows top-level message log::error!("Operation failed: {}", err); // Output: Operation failed: Failed to connect to database
// CORRECT - shows full chain with causes log::error!("Operation failed: {:?}", err); // Output: // Operation failed: Failed to connect to database: postgres://localhost:5432/mydb // // Caused by: // 0: Failed to connect to database: postgres://localhost:5432/mydb // 1: Connection refused (os error 111)
// Or use chain() for custom formatting log::error!("Error chain:"); for (i, cause) in err.chain().enumerate() { log::error!(" {}: {}", i, cause); } } ```
- 1.Use context() with closures for expensive formatting:
- 2.```rust
- 3.use anyhow::Context;
fn process_large_file(path: &Path) -> anyhow::Result<Data> { // context() takes a closure - only evaluated if there is an error let content = std::fs::read(path) .with_context(|| format!( "Failed to read file: {} (size: {} bytes)", path.display(), path.metadata().map(|m| m.len()).unwrap_or(0) ))?;
// For simple messages, use the &str version (no closure overhead) let data = parse_data(&content) .context("Failed to parse data")?;
Ok(data) } ```
- 1.Build custom error reports for API responses:
- 2.```rust
- 3.use anyhow::{Context, Result};
fn api_handler(request: Request) -> Result<Response> { let user = authenticate(&request) .context("Authentication failed")?;
let payload = parse_payload(&request.body) .context("Invalid request payload")?;
let result = process_request(&user, &payload) .context("Request processing failed")?;
Ok(Response::ok(result)) }
// Custom error formatting for API responses fn format_api_error(err: &anyhow::Error) -> ApiErrorResponse { ApiErrorResponse { error: err.to_string(), // Top-level message for user details: if cfg!(debug_assertions) { // In development, show full chain Some(format!("{:?}", err)) } else { // In production, only show user-friendly message None }, } } ```
- 1.**Distinguish between context() and wrap()":
- 2.```rust
- 3.use anyhow::{Context, Result};
- 4.use thiserror::Error;
#[derive(Error, Debug)] enum AppError { #[error("Database error: {0}")] Database(#[from] sqlx::Error), #[error("Validation error: {field}")] Validation { field: String }, }
fn example() -> Result<(), AppError> { // context() converts to anyhow::Error (loses typed error) let data = fetch_data() .context("Network request failed")?; // Returns anyhow::Error
// For typed errors, use map_err or thiserror's #[from] let data = fetch_data() .map_err(AppError::Database)?; // Preserves typed error
Ok(()) } ```
Prevention
- Always use
context()orwith_context()instead ofmap_err(anyhow!(...)) - Log errors with
{:?}format to include the full chain - Include variable values in context messages:
format!("Processing user {}", user.id) - Use
wrap_errfromeyrecrate if you need source chain on non- anyhow errors - Add error chain inspection to runbooks for on-call engineers
- Use
anyhow::Chainiterator for structured error chain processing