Skip to content

Lesson 4 of 9 · 27m

Error Handling Idioms That Scale Beyond Hello World

Model recoverable failure with precise error types, use context without losing causes, and reserve panics for broken invariants.

Production Rust error handling is not a contest between unwrap and purity. It is a design exercise: which failures are expected, which are programming mistakes, what context an operator needs, and what a caller can realistically do about each case. If your error type cannot answer those questions, your service will answer them at 3 a.m. instead.

Expected failure belongs in Result

A network timeout, invalid peer certificate, malformed packet, missing file, or occupied port is expected in a systems program. Put it in the type:

use std::io;

fn load_config(path: &str) -> Result<String, io::Error> {
    std::fs::read_to_string(path)
}

Result is not bureaucracy. It makes failure part of the API contract. The caller can retry, fall back, degrade, or report — but only because the signature admitted failure exists.

Library errors should be specific; application errors can be broad

Libraries should expose actionable distinctions:

#[derive(Debug, thiserror::Error)]
pub enum ListenError {
    #[error("failed to bind {addr}: {source}")]
    Bind { addr: String, source: std::io::Error },
    #[error("invalid TLS identity: {0}")]
    InvalidIdentity(String),
}

Applications often need ergonomic propagation across many subsystems. anyhow::Context is useful there:

use anyhow::Context;

let data = std::fs::read(&path)
    .with_context(|| format!("failed to read identity file {}", path.display()))?;

Do not erase source causes. Context should wrap, not replace. An operator seeing only "internal error" has learned nothing.

Panics are for impossible states, not bad input

Use unwrap, expect, indexing, or assertion when the surrounding invariant makes failure logically impossible — and be able to explain that invariant. Do not panic because a peer sent malformed bytes or because a configuration file is absent.

debug_assert!(window.start <= window.end);
if window.start > window.end {
    return Err(Error::InvalidWindow);
}

A panic across an FFI boundary or inside a worker thread can become an availability bug. A panic caused by untrusted input is worse: it is a remote denial of service primitive.

Error type size is a systems concern

Large error enums can inflate Result<T, E> and affect hot paths. Measure before optimizing, but know the pattern:

type BoxError = Box<dyn std::error::Error + Send + Sync + 'static>;

Boxing type-erased errors is common in application glue. In low-level libraries, precise static errors are usually worth the verbosity because callers can match on them.

Design for the caller's decision

Ask what the caller can do. Retry? Then expose whether the failure is transient. Validate input? Then expose which field failed. Reconnect? Then distinguish handshake failure from an established connection reset. A single stringly typed error cannot support those decisions.

Field notes

  • expect("invariant: ...") is better than bare unwrap because it records why the panic should be impossible.
  • Do not log-and-return errors in libraries; either return the error or handle it fully. Double reporting creates noise.
  • Preserve source chains. Root cause disappears quickly when errors cross module boundaries.
  • Never convert errors with map_err(|_| ...) unless losing the original cause is intentional.

Was this lesson helpful?

Sign in to rate