Sub topic 14
Reducing boilerplate with thiserror and anyhow
This chapter assumes you have read the earlier chapters of this tutorial. You should be comfortable with Result, the ? operator, the From trait, hand-written custom error enums, and Box<dyn Error>. You also need to be able to add a dependency to Cargo.toml.
Writing a custom error type by hand takes three trait implementations: Display, Error, and one From per wrapped error. Two widely used crates remove most of that code:
thiserrorgenerates those implementations for an error type you design. It suits libraries.anyhowprovides one ready-made, catch-all error type with helpers for adding context. It suits applications.
Neither crate changes how ? works. They produce types that ? already knows how to use.
Setting up
Add both crates to a binary project:
[dependencies]
thiserror = "2"
anyhow = "1"A real project often needs only one of them. Libraries usually depend on thiserror alone. Applications often depend on anyhow alone, or on both.
thiserror: generating the boilerplate
thiserror is a derive macro. It runs at compile time and writes the same code you would have written by hand. It adds no runtime cost and no new types to your public API. You can remove it later without breaking callers, as long as you hand-write the same impls.
Here is the ConfigError from the earlier chapter, rewritten with it:
use std::num::ParseIntError;
use thiserror::Error;
#[derive(Debug, Error)]
enum ConfigError {
#[error("missing key: {0}")]
Missing(String),
#[error("port is not a valid number")]
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)
}
fn main() {
println!("{:?}", read_port(Some("8080")));
println!("{}", read_port(None).unwrap_err());
println!("{}", read_port(Some("abc")).unwrap_err());
}The macro does three jobs:
#[derive(Error)]implementsstd::error::Errorfor the enum. You still deriveDebugyourself, becauseErrorrequires it.#[error("...")]implementsDisplay. The string works like aformat!template.{0}refers to the first tuple field. For named fields, write{path}.#[from]implementsFrom<ParseIntError> for ConfigError. It also marks that field as the error'ssource(). This is whytext.parse::<u16>()?still compiles unchanged.
Compare this with the roughly 35 lines the hand-written version needed. The behavior is the same, and ? converts errors the same way.
Attributes you will use
| Attribute | Placed on | Effect |
|---|---|---|
| `#[error("...")]` | Variant or struct | Generates `Display` from a format string |
| `#[from]` | A field | Generates `From<FieldType>` and sets `source()` |
| `#[source]` | A field | Sets `source()` without generating `From` |
| `#[error(transparent)]` | Variant or struct | Forwards `Display` and `source()` to the single inner error |
Adding context with #[source]
#[from] has a limit. It generates From<ParseIntError>, and a type can have only one From impl per source type. Suppose two variants both wrap io::Error. Only one of them could use #[from], and ? could not tell which one you meant. The usual fix is to carry context fields and use #[source], then build the variant yourself with map_err:
use std::fs;
use std::io;
use std::num::ParseIntError;
use thiserror::Error;
#[derive(Debug, Error)]
enum LoadError {
#[error("could not read {path}")]
Read {
path: String,
#[source]
source: io::Error,
},
#[error("{path} does not contain a valid port")]
Port {
path: String,
#[source]
source: ParseIntError,
},
}
fn load_port(path: &str) -> Result<u16, LoadError> {
let text = fs::read_to_string(path).map_err(|source| LoadError::Read {
path: path.to_string(),
source,
})?;
text.trim().parse().map_err(|source| LoadError::Port {
path: path.to_string(),
source,
})
}
fn main() {
if let Err(e) = load_port("port.txt") {
println!("error: {e}");
if let Some(cause) = std::error::Error::source(&e) {
println!("caused by: {cause}");
}
}
}This is more code than #[from], but each error now says which file failed. Callers can also match on the variant to decide what to do.
Avoiding duplicated messages
Be careful when a variant both has a source and prints that source in its own message. Error reporters, including anyhow's, print the message and then walk the source() chain. If your message already contains {0} for the inner error, the same text appears twice. A common convention is that each error describes only its own level and leaves the cause to the chain. That is why BadNumber above does not interpolate the ParseIntError.
anyhow: one error type for applications
An application's top level usually does not need to match on error kinds. It needs to report what went wrong, with enough detail to debug. anyhow is built for that. Its anyhow::Error type is, roughly, a Box<dyn Error + Send + Sync + 'static> with extras: it can capture a backtrace, hold a chain of context messages, and be downcast.
use anyhow::{bail, Context, Result};
use std::fs;
fn load_port(path: &str) -> Result<u16> {
let text = fs::read_to_string(path)
.with_context(|| format!("failed to read {path}"))?;
let port: u16 = text
.trim()
.parse()
.with_context(|| format!("{path} does not contain a valid port"))?;
if port < 1024 {
bail!("port {port} is reserved");
}
Ok(port)
}
fn main() -> Result<()> {
let port = load_port("port.txt")?;
println!("port = {port}");
Ok(())
}If port.txt does not exist, the program exits with a failure status and prints something like this:
Error: failed to read port.txt
Caused by:
No such file or directory (os error 2)The pieces work like this:
anyhow::Result<T>is an alias forResult<T, anyhow::Error>. WritingResult<u16>is enough.?converts anyE: std::error::Error + Send + Sync + 'staticintoanyhow::Errorthrough a blanketFromimpl. This is the same mechanism you used withBox<dyn Error>.- The
Contexttrait adds.context("...")and.with_context(|| ...)toResultandOption. Usewith_contextwhen the message needsformat!. The closure runs only on the error path, so the success path pays nothing. bail!("...")returnsErr(anyhow!("..."))immediately.ensure!(cond, "...")isbail!guarded by a condition.anyhow!("...")builds an error value without returning.- Because
Contextalso works onOption, you can writemap.get("port").context("missing port")?. It replacesok_or_elsewhen you do not need a typed error.
Downcasting
anyhow::Error erases the concrete type, but you can recover it when needed:
use anyhow::Result;
use std::io;
fn open_it() -> Result<()> {
std::fs::File::open("missing.txt")?;
Ok(())
}
fn main() {
let err = open_it().unwrap_err();
match err.downcast_ref::<io::Error>() {
Some(e) if e.kind() == io::ErrorKind::NotFound => println!("file not found"),
Some(e) => println!("other I/O error: {e}"),
None => println!("not an I/O error"),
}
}If you find yourself downcasting often, that is a sign the code wants a typed error enum instead.
Gotchas
anyhow::Errordoes not implementstd::error::Error. It cannot, because that would conflict with its blanketFromimpl. You can pass it where&dyn Erroris needed by calling.as_ref(). Libraries should not put it in their public signatures.- The error must be
Send + Sync + 'static. An error type that holds anRcor a non-'staticborrow will not convert. - Context wraps the error. It does not replace it. The original cause stays in the chain and is shown under "Caused by".
- Printing with
{}shows only the outermost message.{:#}joins the chain on one line, and{:?}shows the full multi-line report.
Choosing between them
The two crates are often combined. Library-style modules inside your application return typed thiserror enums. The top-level code in main uses anyhow::Result, and ? turns each typed error into an anyhow::Error automatically, because the enums implement std::error::Error.
| Concern | thiserror enum | anyhow::Error |
|---|---|---|
| Callers can match on variants | Yes | Only by downcasting |
| Part of a stable public API | Good fit | Poor fit |
| Boilerplate | Low, but variants must be declared | Lowest |
| Adding call-site context | Via fields and `map_err` | `.context(...)` |
| Typical home | Libraries, core modules | `main`, CLIs, scripts |
Common mistakes
- Using
anyhowin a library's public API. Callers lose the ability to match on errors and cannot handle failures selectively. - Two
#[from]fields of the same type. The macro would generate conflictingFromimpls, so compilation fails. Use#[source]andmap_errfor one or both. - Forgetting
Debug.#[derive(Error)]does not derive it for you, and the compiler will complain thatErrorrequiresDebug. - Context that repeats the cause. A message like
.context("error reading file")adds little. Say what you were trying to do and which input was involved.
Exercise
A function returns Result<Config, ConfigError>, where ConfigError is a thiserror enum. Inside it, two different calls both return std::io::Error: one reads the config file, and one reads a secrets file. You want the error to say which file failed. Why does putting #[from] io::Error on two variants not work, and what do you do instead?
Show answer
#[from] generates impl From<io::Error> for ConfigError, and Rust allows only one such impl, so two variants would conflict. Also, ? could not know which variant to build. Give each variant a context field (such as path: String) and a #[source] source: io::Error field, then build the variant yourself with .map_err(|source| ConfigError::ReadConfig { path, source })? at each call site.
Exercise
In an application using anyhow, load_port returns anyhow::Result<u16>. Write the line that reads "port.txt" into a String and, if it fails, reports failed to read port.txt with the I/O error as the cause.
Show answer
let text = std::fs::read_to_string("port.txt").context("failed to read port.txt")?; (with use anyhow::Context; in scope). with_context(|| format!(...)) is also correct when the message needs formatting.