Rust

anyhow for Application Errors

admin by @admin ADMIN
6d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
`anyhow::Result<T>` is `Result<T, anyhow::Error>` — a type-erased error that captures any other error AND adds context via `.context()`. The app-author's pick (use thiserror for libraries).
Rust
Raw
// Cargo.toml: anyhow = "1"
use anyhow::{Context, Result, bail};

fn run() -> Result<()> {
    let config = std::fs::read_to_string("config.toml")
        .context("reading config.toml")?;        // adds breadcrumb if it fails

    let port: u16 = config.trim().parse()
        .with_context(|| format!("parsing port from {config:?}"))?;

    if port == 0 {
        bail!("port cannot be zero");            // shorthand for return Err(anyhow!())
    }
    println!("listening on :{port}");
    Ok(())
}

fn main() {
    if let Err(e) = run() {
        eprintln!("error: {e:#}");               // {:#} prints full causal chain
        std::process::exit(1);
    }
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.