valfz

Error handling in Rust without the ceremony

How to structure errors in a Rust program: what ? expands to, when to panic, error enums by hand and with thiserror, anyhow, and what main prints.

topic
rust
date
read
23 min

Most error-handling decisions in a Rust program reduce to two questions asked at the point of failure: whether this is a bug or something the outside world can cause, and whether the error will be handled by code or read by a person. The answers select the tool: a panic or a Result, a typed enum or an opaque error with context attached.

This article works through each choice on one small program, confcheck, which reads a port setting from a file, and shows what every variant prints. The code was tested with rustc 1.99.1 (edition 2024). cargo add thiserror anyhow resolved to thiserror 2.0.21 and anyhow 1.0.105.

What ? expands to

src/main.rs
use std::fs;
use std::io;
use std::num::ParseIntError;

#[derive(Debug)]
enum PortError {
    Io(io::Error),
    Parse(ParseIntError),
}

impl From<io::Error> for PortError {
    fn from(err: io::Error) -> Self {
        PortError::Io(err)
    }
}

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

fn read_port(path: &str) -> Result<u16, PortError> {
    let text = fs::read_to_string(path)?;
    let port = text.trim().parse::<u16>()?;
    Ok(port)
}

On Ok, ? unwraps the value. On Err, it returns from the function after passing the error through From::from. The next function in the same file spells that out:

src/main.rs
fn read_port_expanded(path: &str) -> Result<u16, PortError> {
    let text = match fs::read_to_string(path) {
        Ok(text) => text,
        Err(err) => return Err(From::from(err)),
    };
    let port = match text.trim().parse::<u16>() {
        Ok(port) => port,
        Err(err) => return Err(From::from(err)),
    };
    Ok(port)
}

The compiler’s own desugaring goes through the unstable Try trait, but for Result it comes to this match. The Reference describes it as Err(e) returning Err(From::from(e)).

That conversion is what lets one function mix failure types. read_to_string fails with io::Error, parse fails with ParseIntError, and each becomes a PortError through its From impl. Delete the second impl and both functions stop compiling. The error for the ? version names the conversion:

error[E0277]: `?` couldn't convert the error to `PortError`
  --> src/main.rs:19:42
   |
17 | fn read_port(path: &str) -> Result<u16, PortError> {
   |                             ---------------------- expected `PortError` because of this
18 |     let text = fs::read_to_string(path)?;
19 |     let port = text.trim().parse::<u16>()?;
   |                            --------------^ the trait `From<ParseIntError>` is not implemented for `PortError`
...

With both impls in place, main matches on the variants and checks that the two versions agree:

src/main.rs
fn main() {
    for path in ["port.txt", "big.txt", "missing.txt"] {
        match read_port(path) {
            Ok(port) => println!("{path}: port {port}"),
            Err(PortError::Io(err)) => println!("{path}: cannot read: {err}"),
            Err(PortError::Parse(err)) => println!("{path}: not a port: {err}"),
        }
        assert_eq!(
            format!("{:?}", read_port(path)),
            format!("{:?}", read_port_expanded(path))
        );
    }
}

port.txt contains 8080, big.txt contains 80800, and there is no missing.txt:

port.txt: port 8080
big.txt: not a port: number too large to fit in target type
missing.txt: cannot read: No such file or directory (os error 2)

? on an Option returns None early in the same way, but the two do not mix. Applying ? to an Option inside a function that returns Result is rejected with E0277, and the compiler’s suggestion is the usual fix: convert with .ok_or(...) first. The load function further down does that.

When panicking is correct

A panic reports a bug: the program reached a state its own logic was supposed to rule out. A Result reports a failure that correct code has to expect, such as a missing file or malformed input. The standard library documentation draws the same line.

unwrap and expect are therefore correct where a failure can only mean the source code is wrong, for example when parsing a constant. They are also the normal way for a test to fail, and acceptable in prototypes and examples whose error paths are not the subject. Prefer expect, with a message that says why the value should be there:

src/main.rs
use std::net::IpAddr;

fn main() {
    let fallback: IpAddr = "127.0.0.256"
        .parse()
        .expect("hardcoded fallback address should parse");
    println!("{fallback}");
}
cargo run -q
echo $?
thread 'main' (1292468) panicked at src/main.rs:6:10:
hardcoded fallback address should parse: AddrParseError(Ip)
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
101

The message is written for a developer: a source location, the sentence passed to expect, and the Debug form of the error. Since the error value is printed anyway, the std documentation recommends wording the sentence as the precondition that should have held, which adds information the error does not have. The exit status is 101. Nobody running the program can fix a bad octet in a string literal, so a panic is the honest outcome here. Anything that depends on input, the file system or the network belongs in a Result. In library code the bar is higher still, because a panic removes the caller’s chance to decide.

A library error type, written by hand

Code that other code calls should fail with a type the caller can match on. The conventions for such a type are in the Error trait documentation: keep Display messages short and lowercase with no trailing punctuation, return the underlying cause from source(), and leave the cause’s text out of your own message so that it is not printed twice.

src/config.rs
use std::error::Error;
use std::fmt;
use std::fs;
use std::io;
use std::num::ParseIntError;
use std::path::{Path, PathBuf};

#[derive(Debug)]
pub enum ConfigError {
    Read {
        path: PathBuf,
        source: io::Error,
    },
    MissingKey {
        key: &'static str,
    },
    InvalidPort {
        value: String,
        source: ParseIntError,
    },
}

impl fmt::Display for ConfigError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ConfigError::Read { path, .. } => write!(f, "cannot read {}", path.display()),
            ConfigError::MissingKey { key } => write!(f, "missing key `{key}`"),
            ConfigError::InvalidPort { value, .. } => write!(f, "invalid port `{value}`"),
        }
    }
}

impl Error for ConfigError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match self {
            ConfigError::Read { source, .. } => Some(source),
            ConfigError::MissingKey { .. } => None,
            ConfigError::InvalidPort { source, .. } => Some(source),
        }
    }
}

#[derive(Debug)]
pub struct Config {
    pub port: u16,
}

pub fn load(path: &Path) -> Result<Config, ConfigError> {
    let text = fs::read_to_string(path).map_err(|source| ConfigError::Read {
        path: path.to_path_buf(),
        source,
    })?;

    let value = text
        .lines()
        .filter_map(|line| line.split_once('='))
        .find(|(key, _)| key.trim() == "port")
        .map(|(_, value)| value.trim())
        .ok_or(ConfigError::MissingKey { key: "port" })?;

    let port = value.parse().map_err(|source| ConfigError::InvalidPort {
        value: value.to_string(),
        source,
    })?;

    Ok(Config { port })
}

Each variant carries what only this layer knows: which path, which value. That is the reason load uses map_err where the first section used a From impl and a bare ?. An io::Error converted automatically would print No such file or directory (os error 2) and leave out the file name.

A published crate has one more decision to make. Adding a variant to a public enum breaks every downstream match that lists the variants. Marking the enum #[non_exhaustive] makes other crates include a wildcard arm (rustc enforces it with E0004), which leaves room to add variants in a minor release.

The caller prints the error and then walks the source() chain:

src/main.rs
mod config;

use std::error::Error;
use std::path::Path;
use std::process::ExitCode;

fn main() -> ExitCode {
    let Some(path) = std::env::args().nth(1) else {
        eprintln!("usage: confcheck <config-file>");
        return ExitCode::from(2);
    };

    match config::load(Path::new(&path)) {
        Ok(config) => {
            println!("port = {}", config.port);
            ExitCode::SUCCESS
        }
        Err(err) => {
            eprintln!("error: {err}");
            let mut source = err.source();
            while let Some(cause) = source {
                eprintln!("  caused by: {cause}");
                source = cause.source();
            }
            ExitCode::FAILURE
        }
    }
}

There is no missing.conf, big.conf sets port = 80800, and noport.conf has no port line:

cargo run -q -- missing.conf
cargo run -q -- big.conf
cargo run -q -- noport.conf
error: cannot read missing.conf
  caused by: No such file or directory (os error 2)
error: invalid port `80800`
  caused by: number too large to fit in target type
error: missing key `port`

The same type with thiserror

src/config.rs
use thiserror::Error;

#[derive(Debug, Error)]
pub enum ConfigError {
    #[error("cannot read {}", .path.display())]
    Read { path: PathBuf, source: io::Error },

    #[error("missing key `{key}`")]
    MissingKey { key: &'static str },

    #[error("invalid port `{value}`")]
    InvalidPort {
        value: String,
        source: ParseIntError,
    },
}

The derive replaces the two hand-written impl blocks, and the thiserror::Error import takes the place of std::error::Error and std::fmt. load and main stay as they were, and the three runs above print the same text.

Dumping the macro expansion for this file shows what the derive wrote: an impl Display with one match arm per #[error] attribute, and an impl Error whose source() returns the field named source. A field with another name can be marked #[source]. That is the previous listing, generated. Both impls are of std traits, so thiserror stays out of your public API and callers cannot tell which form you used. The crate documentation states this as a design goal.

#[from] on a field also generates the From impl from the first section, which brings back the bare ?. It fits variants where the source alone tells the whole story:

src/main.rs
#[derive(Debug, Error)]
enum PortError {
    #[error("cannot read the port file")]
    Io(#[from] io::Error),

    #[error("the port file does not hold a port number")]
    Parse(#[from] ParseIntError),
}

With this enum, read_port from the first section compiles unchanged.

Application errors with anyhow

At the top of an application nobody matches on variants. Errors are logged or shown to a person, and what is usually missing is a statement of what the program was trying to do. anyhow::Error can hold any error type that is Send, Sync and 'static, ? converts into it with no From impl of your own, and .context() wraps the error in one more message.

src/main.rs
mod config;

use std::path::Path;

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

fn main() -> Result<()> {
    let path = std::env::args()
        .nth(1)
        .context("usage: confcheck <config-file>")?;

    let config = config::load(Path::new(&path)).context("could not load server configuration")?;

    if config.port < 1024 {
        bail!("port {} needs root; pick 1024 or above", config.port);
    }

    println!("port = {}", config.port);
    Ok(())
}

config.rs is the thiserror version, and low.conf sets port = 80:

cargo run -q -- missing.conf
cargo run -q -- low.conf
Error: could not load server configuration

Caused by:
    0: cannot read missing.conf
    1: No such file or directory (os error 2)
Error: port 80 needs root; pick 1024 or above

The first error has three layers: the application’s context, the library’s ConfigError, and the OS error underneath. The multi-line layout is anyhow’s {:?} output. Printing the same error with {} and then with {:#} gives the outermost message alone, then the whole chain on one line, which suits a log:

could not load server configuration
could not load server configuration: cannot read missing.conf: No such file or directory (os error 2)

Two details are useful in practice. .with_context(|| format!(...)) takes a closure, so a formatted message is built on the failure path only. With RUST_BACKTRACE=1 set, the {:?} output also ends with a stack backtrace captured where the error entered anyhow, which in this program is the .context() call in main.

The typed error is still inside. err.downcast_ref::<ConfigError>() returns it for the rare caller that needs to branch. Keep anyhow in binaries, though: a library function that returns anyhow::Error gives its callers nothing to match on.

When Box<dyn Error> is enough

src/main.rs
use std::error::Error;
use std::fs;

fn read_port(path: &str) -> Result<u16, Box<dyn Error>> {
    let text = fs::read_to_string(path)?;
    let port = text.trim().parse::<u16>()?;
    if port < 1024 {
        return Err(format!("port {port} needs root").into());
    }
    Ok(port)
}

fn main() -> Result<(), Box<dyn Error>> {
    let path = std::env::args()
        .nth(1)
        .ok_or("usage: confcheck <port-file>")?;
    let port = read_port(&path)?;
    println!("port = {port}");
    Ok(())
}

This needs no dependency. ? accepts any error type through a blanket From impl in std, and strings convert too, which is what .into() and ok_or("...")? rely on. For a script-sized tool, an example or a test helper, that is enough.

cargo run -q -- missing.txt
cargo run -q -- low.txt
Error: Os { code: 2, kind: NotFound, message: "No such file or directory" }
Error: "port 80 needs root"

Compared with anyhow, there is no .context(), so the first line cannot name the file, and main prints the Debug form of whatever was in the box, quotes included. Box<dyn Error> is also not Send: thread::spawn rejects a function that returns it with E0277, and Box<dyn Error + Send + Sync> is the spelling that crosses threads.

Keep dependency types out of public errors

ConfigError exposes io::Error and ParseIntError in its variants. That is safe, because std does not ship breaking releases. A type from another crate is different. Here is an error for a JSON manifest parsed with serde_json 1.0.154:

src/manifest.rs
#[derive(Debug, Error)]
pub enum ManifestError {
    #[error("manifest is not valid JSON")]
    Json(#[from] serde_json::Error),

    #[error("manifest has no `name` field")]
    MissingName,
}

serde_json::Error is now part of this crate’s public API twice: as the type of a public field, and through a public From impl. A caller can write Err(ManifestError::Json(err)) => println!("bad JSON on line {}", err.line()), which calls serde_json’s API through your type. From then on, replacing the parser or moving to a new major version of it is a breaking change for your own users.

The alternative is to copy out the facts you are willing to promise and erase the type of the rest:

src/manifest.rs
use std::error::Error as StdError;

use thiserror::Error;

#[derive(Debug, Error)]
pub enum ManifestError {
    #[error("manifest is not valid JSON (line {line}, column {column})")]
    Syntax {
        line: usize,
        column: usize,
        source: Box<dyn StdError + Send + Sync>,
    },

    #[error("manifest has no `name` field")]
    MissingName,
}

pub fn package_name(text: &str) -> Result<String, ManifestError> {
    let value: serde_json::Value =
        serde_json::from_str(text).map_err(|err| ManifestError::Syntax {
            line: err.line(),
            column: err.column(),
            source: err.into(),
        })?;

    value["name"]
        .as_str()
        .map(str::to_string)
        .ok_or(ManifestError::MissingName)
}

Printed with the same chain walk as before, for a manifest with an unquoted value on line 2:

error: manifest is not valid JSON (line 2, column 11)
  caused by: expected value at line 2 column 11

The public type names std types only, and the chain still carries the parser’s message. A caller can downcast the boxed source back to serde_json::Error, but nothing in your signatures promises that will keep working.

What main prints and returns

main may return any type that implements Termination, and Result<(), E> does whenever E implements Debug. On Err, the runtime prints Error: followed by the Debug form of the error to stderr and exits with status 1. With the thiserror ConfigError:

src/main.rs
mod config;

use std::path::Path;

fn main() -> Result<(), config::ConfigError> {
    let config = config::load(Path::new("missing.conf"))?;
    println!("port = {}", config.port);
    Ok(())
}
cargo run -q
echo $?
Error: Read { path: "missing.conf", source: Os { code: 2, kind: NotFound, message: "No such file or directory" } }
1

The Display messages written earlier never appear, because Debug is what gets printed. anyhow’s Debug impl is designed for this spot, which is why returning anyhow::Result<()> from main produced a readable chain in the anyhow section.

For control over both the text and the status, return ExitCode and print the error yourself, as the hand-written main did. Run without an argument, that version exits with the code it reserves for usage errors:

cargo run -q
echo $?
usage: confcheck <config-file>
2

A shell script can therefore tell the cases apart: 101 for a panic, 1 for an Err returned from main, and any other value you return through ExitCode.

keyboard

h
home
w c a
writing, courses, about
n p
next and previous lesson
j k
scroll down and up
g G
top and bottom of the page
t
switch light and dark
?
this help

shortcuts are