Skip to content

Lesson 4 of 9 · 27m

Error Ergonomics with anyhow and thiserror

Choose application errors versus library errors deliberately, preserve context, and print diagnostics users can act on without exposing internals.

Bad error handling in Rust rarely fails because Result is hard. It fails because the team never decided who errors are for. Library consumers need typed errors they can match. Operators need context, causes, and a next action. End users need neither a panic nor a wall of macro-expanded type noise. anyhow and thiserror solve different halves of that problem.

Use thiserror where callers need control flow

A reusable crate should expose meaningful failure categories:

use thiserror::Error;

#[derive(Debug, Error)]
pub enum RegistryError {
    #[error("artifact `{0}` was not found")]
    ArtifactMissing(String),
    #[error("registry authentication failed")]
    Authentication(#[source] reqwest::Error),
    #[error("registry returned invalid metadata")]
    InvalidMetadata(#[from] serde_json::Error),
}

The point is not merely prettier Display implementations. It is that another program can distinguish "missing object" from "bad credentials" without parsing prose.

Use anyhow at the application boundary

In a binary, errors often cross filesystem, network, serialization, and business logic boundaries. anyhow::Result keeps the application moving while preserving the chain:

use anyhow::{Context, Result};
use std::fs;

fn load_manifest(path: &str) -> Result<Manifest> {
    let raw = fs::read_to_string(path)
        .with_context(|| format!("failed to read manifest at {path}"))?;
    serde_json::from_str(&raw)
        .with_context(|| format!("failed to parse manifest at {path}"))
}

Context answers "what operation failed?" The source error answers "why?" You need both.

Design the user-facing report

Do not dump Debug output as the primary interface. Print a concise error, then causal detail when verbose logging is enabled:

error: failed to publish artifact dist/app.tar.gz
caused by: registry authentication failed
caused by: HTTP 401 from https://registry.sudosecurity.org/v1/tokens
hint: run `deployctl auth login` or check DEPLOYCTL_TOKEN

Hints are high leverage because they convert failure into action. Keep them specific. "Try again later" is not a hint; it is surrender.

Panics are bugs, not error handling

unwrap is appropriate in tests, examples, and invariants you can prove. It is not appropriate for user input, network state, file existence, or permissions. If you do keep an invariant assertion, write the invariant into the message:

let first = chunks.first().expect("nonempty input was validated before chunking");

When that panic appears in a crash report, the message tells the maintainer which assumption broke.

Do not leak operational secrets through context

Context strings often include paths, URLs, headers, usernames, or request bodies. Treat them as sensitive until proven otherwise. Redact tokens, never attach entire authorization headers, and remember that shell history plus verbose output can accidentally preserve credentials.

Field notes

  • #[from] is convenient but can overfit your public API to dependency types; sometimes a manual variant preserves flexibility.
  • The error chain is diagnostic data, not a substitute for metrics or structured logs.
  • main() -> anyhow::Result<()> prints reasonable errors, but production CLIs often need explicit formatting and exit-code mapping.
  • Error messages should name the operation and object, not merely the failed syscall.
  • Do not attach user-controlled text to errors without considering terminal control characters.

Was this lesson helpful?

Sign in to rate