Sub topic 16
Error handling crates in practice
This chapter assumes you can write a custom error enum with Display, Error, and From, and that you use ? and Box<dyn Error>. It shows the two crates that remove most of that boilerplate. They are thiserror and anyhow.
The problem the crates solve
Writing a custom error by hand takes three pieces: the enum, a Display implementation, and one From implementation for each source error. The code is simple but repetitive. Box<dyn Error> avoids the repetition, but it gives you no context and no way to match on specific variants.
Two crates cover these cases:
thiserrorgenerates theDisplay,Error, andFromimplementations for an enum you define.anyhowprovides one ready-made error type that can wrap any error and carry extra context messages.
Add both to Cargo.toml:
[dependencies]
thiserror = "1"
anyhow = "1"thiserror: typed errors for libraries
#[derive(Error)] writes the trait implementations. #[error("...")] becomes the Display text. #[from] generates the From implementation, so ? converts the source error for you.
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"))?;
Ok(text.parse::<u16>()?)
}
fn main() {
println!("{:?}", read_port(Some("8080")));
match read_port(Some("abc")) {
Err(e) => println!("{e}"),
Ok(p) => println!("{p}"),
}
}This is the same ConfigError you wrote by hand earlier, in about a third of the lines. Callers can still match on Missing and BadNumber.
anyhow: flexible errors for applications
anyhow::Error wraps any error type. The Context trait adds a message at each layer. It works on both Result and Option.
use anyhow::{Context, Result};
fn load_port(value: Option<&str>) -> Result<u16> {
let text = value.context("port is not set")?;
let port = text
.parse::<u16>()
.with_context(|| format!("invalid port {text:?}"))?;
Ok(port)
}
fn main() -> Result<()> {
println!("{}", load_port(Some("8080"))?);
println!("{}", load_port(Some("abc"))?);
Ok(())
}The second call makes main return an error. Rust prints the message and the chain of causes, which here is invalid port "abc" followed by invalid digit found in string.
Use context for a fixed message. Use with_context when building the message costs something, because it runs only on failure.
Choosing between them
| Question | thiserror | anyhow |
|---|---|---|
| Typical use | Libraries | Applications and scripts |
| Error type | Your own enum | One opaque type |
| Callers can match variants | Yes | Only through downcasting |
| Adds context messages | You design them | `context` and `with_context` |
The two combine well. A library module returns thiserror enums, and the application's top level converts them into anyhow::Error with ? and adds context.
Common mistakes
- Returning
anyhow::Resultfrom a public library function. Callers cannot match on the failure cases. - Using
#[from]for two variants with the same source type. The derive generates conflictingFromimplementations and will not compile. - Adding a dependency for a three-variant error enum in a small program. The hand-written version is fine there.
Exercise
A command-line tool reads a config file, parses numbers, and exits on the first failure with a readable message that names the file. Which crate fits the top-level code, and which method adds the file name?
Show answer
Use anyhow. Call with_context(|| format!("failed to read {path}")) on the fallible call. This attaches the file name only when an error occurs, and main returning anyhow::Result<()> prints the message and its causes.