Sub topic 14
Reducing boilerplate with thiserror and anyhow
This chapter assumes you have read the earlier chapters. You should know how ? uses From to convert errors, how to write a custom error enum with Display, Error, and From, and how Box<dyn Error> works. You also need to be able to add a dependency with Cargo.
What the crates do
The custom error type from the earlier chapter needed three hand-written implementations: Display, Error (with source), and From<ParseIntError>. Two crates by the same author remove that boilerplate. They cover different needs:
thiserrorgenerates those implementations for an error type you define. It is meant for libraries, where callers need to match on specific variants.anyhowprovides one ready-made error type,anyhow::Error, that wraps any error. It is meant for applications, where you mostly report errors and don't inspect them.
Add them with Cargo:
cargo add thiserror anyhowthiserror: derive the boilerplate
This is the ConfigError from before, rewritten with thiserror. The #[error(...)] attribute generates Display. #[from] generates the From implementation and also makes the wrapped error the source.
use std::num::ParseIntError;
use thiserror::Error;
#[derive(Debug, Error)]
enum ConfigError {
#[error("missing key: {0}")]
Missing(String),
#[error("invalid number: {0}")]
BadNumber(#[from] ParseIntError),
}
fn read_port(value: Option<&str>) -> Result<u16, ConfigError> {
let text = value.ok_or_else(|| ConfigError::Missing("port".to_string()))?;
let port = text.parse::<u16>()?;
Ok(port)
}The function body is unchanged. The ? after parse still converts ParseIntError into ConfigError through From. Only the type definition got shorter, from about thirty lines to about eight.
thiserror adds no runtime cost and does not appear in your public API. Callers see an ordinary enum that implements std::error::Error.
anyhow: one error type for applications
anyhow::Error works like Box<dyn Error> with extras. Any error type can be converted into it with ?. It can also carry a chain of context messages, and it can capture a backtrace when the RUST_BACKTRACE environment variable is set.
use anyhow::{Context, Result};
use std::fs;
fn main() -> Result<()> {
let text = fs::read_to_string("count.txt")
.context("could not read count.txt")?;
let count: u32 = text
.trim()
.parse()
.context("count.txt must contain a number")?;
println!("count = {count}");
Ok(())
}anyhow::Result<T> is an alias for Result<T, anyhow::Error>. The .context(...) method wraps the original error with a message. If the file is missing, the program prints your message followed by a Caused by: line with the operating system error.
Choosing between them
The two are often combined. A library crate exposes a thiserror enum, and the application that uses it converts that enum into anyhow::Error with ?. This works because anyhow::Error can be built from any error that is Send + Sync + 'static.
Trade-offs
| Need | thiserror | anyhow |
|---|---|---|
| Match on specific errors | Yes, enum variants | Only by downcasting |
| Add context messages | Write a variant for each | `.context(...)` anywhere |
| Setup effort | Define a type | None |
| Best fit | Libraries | Applications and scripts |
Both are optional. For a small program, Box<dyn Error> from the standard library is often enough. Reach for these crates when the manual version starts to feel repetitive.
Exercise
A command-line tool reads a config file, parses a port number, and prints a message on failure. Which crate fits the error handling in main, and which method adds the text "could not parse port" to a failing parse call?
Show answer
Use anyhow, because the tool only reports errors and does not need to match on them. Call .context("could not parse port")? on the Result returned by parse. This requires use anyhow::Context;.