Anyhow Context Error Chains

Enrich errors with anyhow context layers, converting foreign error types into chains that print root causes and section context.

RustResilience

Code

rustsnippet
46 lines
use anyhow::{anyhow, Context, Result};
use std::fs;
use std::path::Path;

fn load_config(path: &Path) -> Result<String> {
    fs::read_to_string(path)
        .with_context(|| format!("reading config from {}", path.display()))
}

fn parse_port(raw: &str) -> Result<u16> {
    raw.trim()
        .parse::<u16>()
        .context("port must be 1-65535")
        .with_context(|| format!("invalid port field: {raw:?}"))
}

fn bootstrap(path: &Path) -> Result<()> {
    let content = load_config(path)?;

    let port = content
        .lines()
        .find(|l| l.starts_with("port="))
        .and_then(|l| l.split('=').nth(1))
        .ok_or_else(|| anyhow!("config missing required field: port"))?;

    let parsed = parse_port(port)?;
    println!("bootstrap ok, listening on {parsed}");
    Ok(())
}

fn main() {
    let path = Path::new("app.conf");

    match bootstrap(path) {
        Ok(()) => println!("done"),
        Err(err) => {
            // 链式打印:每层 context 依次列出,根因最后
            let mut chain = err.chain();
            println!("error: {}", chain.next().unwrap());
            for cause in chain {
                println!("  caused by: {cause}");
            }
            println!("backtrace available: {}", err.backtrace().status().is_enabled());
        }
    }
}

What the code does

The working surface is the functions load_config, parse_port, bootstrap and main — everything else is wiring.

The cycling part of this snippet is for cause in chain. Fallible operations return Result, and the ? operator short-circuits errors up to the caller. A match enumerates the value’s possible shapes, and the compiler rejects any arm you forget.

Points of care

  • External dependency: anyhow:: and in — install them before running the snippet.
  • Errors travel through Result; if you drop the ? operators while adapting, each call site needs its own match.

Applying it

The main signature reads fn load_config(path: &Path) -> Result<String>

The run emits 5 labeled sections — bootstrap ok, listening on, done, error:, caused by:, backtrace available: — one per step.

The sequence bootstrap lives in main; running the file triggers it.

Statements that matter

Err(err) => {
    // 链式打印:每层 context 依次列出,根因最后
    let mut chain = err.chain();
    println!("error: {}", chain.next().unwrap());
    for cause in chain {
        println!("  caused by: {cause}");
    }
    println!("backtrace available: {}", err.backtrace().status().is_enabled());
}
.ok_or_else(|| anyhow!("config missing required field: port"))?;
fn load_config(path: &Path) -> Result<String> {
    fs::read_to_string(path)
        .with_context(|| format!("reading config from {}", path.display()))
}

Interactive Tools for This Topic

FAQ

How are errors reported?
Through `Result` values propagated with the `?` operator. Nothing panics inside the snippet; the caller decides how to handle each failure.
Which packages must be installed first?
Yes. The imports resolve to `anyhow::` and `in`, which the package manager must provide.