Sub topic 16
Error handling crates in practice
This chapter assumes you can write a custom error enum and implement Display, Error, and From by hand. It also assumes you know how ? converts errors and how Box<dyn Error> works. Two crates, thiserror and anyhow, remove most of the repetitive code from that work. Here you will learn what each crate does, how they fit together, and how to choose between them.
What the standard library leaves to you
The ConfigError enum from earlier chapters needed three hand-written pieces: a Display implementation, an empty impl std::error::Error, and a From implementation for each wrapped error. None of these pieces is hard, but they grow with every variant. Box<dyn Error> avoids the boilerplate, but it gives you no context messages and no easy way to match on error kinds.
The two crates address different halves of the problem:
| Crate | Solves | Output type | Typical user |
|---|---|---|---|
| `thiserror` | Writing `Display`, `Error`, and `From` for your own enum | Your own enum, unchanged | Libraries, modules with callers who match on errors |
| `anyhow` | Passing any error up with added context | `anyhow::Error`, one opaque type | Applications, binaries, scripts |
Both crates are ordinary dependencies, not language features. Add them to Cargo.toml:
[dependencies]
thiserror = "2"
anyhow = "1"thiserror: generate the boilerplate
thiserror provides a derive macro. You describe each variant with attributes, and the macro writes the trait implementations for you. The enum stays a normal enum, so callers can still match on it.
use std::num::ParseIntError;
use thiserror::Error;
#[derive(Debug, Error)]
enum ConfigError {
#[error("missing key: {0}")]
Missing(&'static str),
#[error("bad number: {0}")]
BadNumber(#[from] ParseIntError),
}
fn read_port(value: Option<&str>) -> Result<u16, ConfigError> {
let text = value.ok_or(ConfigError::Missing("port"))?;
let port = text.parse::<u16>()?;
Ok(port)
}
fn main() {
println!("{:?}", read_port(Some("8080")));
println!("{}", read_port(None).unwrap_err());
println!("{}", read_port(Some("abc")).unwrap_err());
}This produces the same behavior as the hand-written version:
#[error("...")]generates theDisplayimplementation. Placeholders such as{0}refer to tuple fields. Named fields use{name}.#[from]generatesimpl From<ParseIntError> for ConfigError. That is whytext.parse::<u16>()?compiles without amap_err.#[from]also marks the field as the error'ssource(). Tools that walk the error chain can then see the underlyingParseIntError.
The macro generates no code that you could not have written yourself, and it adds nothing to your public API beyond the trait implementations. A caller that depends on your crate does not need thiserror in its own dependency list.
Common thiserror mistakes
- Two
#[from]fields of the same type. Each source type can convert into your enum in only one way. IfReadandWritevariants both wrapstd::io::Error, use#[source]on both fields and build the variants withmap_err. - Forgetting
Debug. TheErrortrait requiresDebug, so keep#[derive(Debug, Error)]. - Putting the source into the message and also exposing it. Printing
{0}for a wrapped error and also returning it fromsource()makes chain-printing tools show the same text twice. Pick one: either a short message with the source in the chain, or a self-contained message.
anyhow: one error type for the whole application
In a binary, nobody is going to match on the error. The program reports it and exits. anyhow::Error is a wrapper that can hold any error implementing std::error::Error, so ? works on every fallible call with no conversion code.
anyhow also adds the part Box<dyn Error> lacks, which is context. The Context trait adds .context() and .with_context() to both Result and Option.
use anyhow::{bail, Context, Result};
fn read_port(value: Option<&str>) -> Result<u16> {
let text = value.context("port is not set")?;
let port: u16 = text
.trim()
.parse()
.with_context(|| format!("invalid port {text:?}"))?;
if port < 1024 {
bail!("port {port} is reserved");
}
Ok(port)
}
fn main() -> Result<()> {
println!("{}", read_port(Some("8080"))?);
println!("{}", read_port(Some("abc"))?);
Ok(())
}Running this prints 8080, then exits with a report that lists the whole chain:
Error: invalid port "abc"
Caused by:
invalid digit found in stringKey points about this code:
anyhow::Result<T>is an alias forResult<T, anyhow::Error>. Theuse anyhow::Resultimport shadows the standardResultin this file..context("...")on anOptionturnsNoneinto an error, so it replacesok_orfor the common case..with_context(|| ...)takes a closure, so the message string is built only when an error actually occurs. Prefer it when the message usesformat!.bail!(...)returns early with a new error.ensure!(condition, "...")is the same check in one line.- Returning
anyhow::Result<()>frommaingives you the chain report shown above instead of the plainDebugoutput you saw earlier.
Inspecting an anyhow error
An anyhow::Error hides the concrete type, but it does not destroy it. You can recover it with downcast_ref:
use anyhow::Result;
use std::num::ParseIntError;
fn parse(s: &str) -> Result<u16> {
Ok(s.parse::<u16>()?)
}
fn main() {
let err = parse("abc").unwrap_err();
match err.downcast_ref::<ParseIntError>() {
Some(e) => println!("parse problem: {e}"),
None => println!("something else: {err}"),
}
}If you find yourself downcasting often, that is a signal the code wants a typed enum instead.
Using both together
The two crates are not rivals. A common layout puts a typed error at each library boundary and anyhow at the top of the application, where errors are only reported.
use anyhow::{Context, Result};
use std::num::ParseIntError;
use thiserror::Error;
#[derive(Debug, Error)]
enum PortError {
#[error("port is empty")]
Empty,
#[error("port is not a number")]
NotNumber(#[from] ParseIntError),
}
fn parse_port(s: &str) -> Result<u16, PortError> {
if s.is_empty() {
return Err(PortError::Empty);
}
Ok(s.parse()?)
}
fn main() -> Result<()> {
let port = parse_port("80x").context("reading the listen port")?;
println!("listening on {port}");
Ok(())
}In main, ? converts PortError into anyhow::Error. This works because PortError implements std::error::Error, which is exactly what thiserror generated. The inner function keeps a precise return type, and the outer function adds human-readable context.
Decision criteria
Use these questions in order:
- Will code outside your crate handle specific failures differently? Define an enum, with or without
thiserror. An opaque error type forces callers to parse message strings. - Is this a binary, a test helper, or a script? Use
anyhow. The only consumer is a person reading a message. - Is the error part of a stable public API? Be careful with
anyhow::Errorin public signatures. It commits your crate to that dependency and removes callers' ability to match. - Is the crate tiny with one or two failure modes? Hand-written code is fine. Adding a dependency to save twenty lines is a trade-off, not an obligation.
Costs and failure modes
- Compile time. Both crates use procedural macros or extra generics, which add a small amount to build time. For most projects the effect is not measurable.
- Backtraces.
anyhowcaptures a backtrace when theRUST_BACKTRACE=1environment variable is set and the toolchain supports it. This can be useful, but it has a runtime cost on error paths, so avoid creating errors in hot loops for control flow. - Context overload. Adding
.context()at every layer produces long chains. Add context where it contains new information, such as a file name or a user ID, and not merely to restate the function name. - Lost matching. Once an error becomes
anyhow::Error, matching on its kind requiresdowncast_ref. Convert late, nearmain, not early.
Exercise
A library function load(path: &str) can fail with an std::io::Error while reading and a ParseIntError while parsing. Callers of the library want to retry only on I/O errors. Should load return anyhow::Result or a thiserror enum, and how would you declare the variants?
Show answer
Return a thiserror enum, because callers must tell the two failures apart. Declare #[derive(Debug, Error)] enum LoadError { #[error("read failed: {0}")] Io(#[from] std::io::Error), #[error("bad number: {0}")] Parse(#[from] ParseIntError) }. Each source type appears once, so both #[from] attributes are allowed and ? converts both automatically. The caller can then write match err { LoadError::Io(_) => retry(), LoadError::Parse(_) => give_up() }. The application's main can still convert LoadError into anyhow::Error with ?.
Exercise
What is the difference between .context("msg") and .with_context(|| format!(...)), and when does the difference matter?
Show answer
Both attach a message to the error. .context takes a value that is built before the call, even when the operation succeeds. .with_context takes a closure that runs only on failure. The difference matters when building the message allocates, such as with format!, on a path that usually succeeds. In that case use .with_context.