FerrousPath

Level 2 · Practitioner· Lesson 6 of 8 · 20 min

Error handling in depth

Designing error types, converting with From, error chains, and when to reach for thiserror and anyhow.

The Error trait

pub trait Error: Debug + Display {
    fn source(&self) -> Option<&(dyn Error + 'static)> { None }
}

An error type should be printable for users (Display), printable for developers (Debug), and able to name the lower-level error that caused it (source).

Conversions with From

? does not merely return the error; it returns From::from(error). Implement From for each underlying error and a function can mix failures freely:

use std::fmt;
use std::num::ParseIntError;

#[derive(Debug)]
enum AppError {
    Parse(ParseIntError),
    Negative(i64),
    Empty,
}

impl fmt::Display for AppError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            AppError::Parse(_) => write!(f, "input is not a number"),
            AppError::Negative(n) => write!(f, "{n} is negative"),
            AppError::Empty => write!(f, "no input"),
        }
    }
}

impl std::error::Error for AppError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            AppError::Parse(e) => Some(e),
            _ => None,
        }
    }
}

impl From<ParseIntError> for AppError {
    fn from(e: ParseIntError) -> Self {
        AppError::Parse(e)
    }
}

fn sqrt_of(input: &str) -> Result<f64, AppError> {
    let input = input.trim();
    if input.is_empty() {
        return Err(AppError::Empty);
    }
    let n: i64 = input.parse()?; // ParseIntError → AppError via From
    if n < 0 {
        return Err(AppError::Negative(n));
    }
    Ok((n as f64).sqrt())
}

fn report(e: &dyn std::error::Error) {
    print!("error: {e}");
    let mut cause = e.source();
    while let Some(c) = cause {
        print!(" ← caused by: {c}");
        cause = c.source();
    }
    println!();
}

fn main() {
    for input in ["144", "", "-4", "12abc"] {
        match sqrt_of(input) {
            Ok(v) => println!("{v}"),
            Err(e) => report(&e),
        }
    }
}

thiserror: the same thing without the boilerplate

For libraries, the thiserror crate derives all three implementations:

// crate: thiserror
use thiserror::Error;

#[derive(Debug, Error)]
enum AppError {
    #[error("input is not a number")]
    Parse(#[from] std::num::ParseIntError),
    #[error("{0} is negative")]
    Negative(i64),
    #[error("no input")]
    Empty,
}

fn parse(s: &str) -> Result<i64, AppError> {
    if s.is_empty() {
        return Err(AppError::Empty);
    }
    let n: i64 = s.parse()?;
    if n < 0 { Err(AppError::Negative(n)) } else { Ok(n) }
}

fn main() {
    for s in ["7", "", "-1", "x"] {
        println!("{:?}", parse(s).map_err(|e| e.to_string()));
    }
}

#[from] generates the From implementation and wires up source. The generated code is what you would have written by hand, and thiserror does not appear in your public API.

anyhow: one error type for applications

An application usually does not match on error variants — it reports them. anyhow::Error holds any error and lets you attach context as it travels upward:

// crate: anyhow
use anyhow::{bail, Context, Result};

fn load_port(path: &str) -> Result<u16> {
    let text = std::fs::read_to_string(path)
        .with_context(|| format!("could not read config file `{path}`"))?;
    let port: u16 = text.trim().parse().context("port is not a number")?;
    if port < 1024 {
        bail!("port {port} is privileged");
    }
    Ok(port)
}

fn main() {
    if let Err(e) = load_port("/no/such/file.conf") {
        println!("{e:#}"); // {:#} prints the whole chain on one line
    }
}

Context is what turns No such file or directory into a message someone can act on.

Guidelines

  • Libraries: return a concrete error enum (often via thiserror). Callers can match on it, and you are not imposing a dependency choice on them. Mark it #[non_exhaustive] if you may add variants.
  • Applications: use anyhow (or eyre) and add context at each layer.
  • Do not unwrap in library code unless a violated invariant truly is a bug.
  • Do not stringify errors early. Result<T, String> discards structure the caller might need.
  • Panic on bugs, return Err on failures. A function whose documentation says “panics if index >= len” is describing a caller bug.
  • Convert an Option with ok_or / ok_or_else; transform errors with map_err; recover with or_else and unwrap_or_else.

Exercises

  1. Write an enum ReadError { Io(std::io::Error), Parse { line: usize, source: ParseIntError } } by hand, with Display, Error::source, and From<io::Error>.
  2. Write fn read_numbers(path: &str) -> Result<Vec<i64>, ReadError> that reports the line number of the first bad line.
  3. Rewrite both with thiserror, then write a main using anyhow that adds the file name as context.

Check your understanding

Pick an answer to see the explanation.

  1. 1.How does ? convert an io::Error into your own AppError?

  2. 2.Which crate is intended for libraries that expose a precise, matchable error enum?

  3. 3.What does Error::source() return?

Finished the lesson and the exercises?