Sub topic 4
Removing the boilerplate with thiserror
This chapter assumes you have read the previous chapters. You should know the Error trait, the hand-written ConfigError with its Display, Error and From impls, and how to add a dependency with Cargo.
What thiserror does
thiserror is a derive macro crate. It writes the same trait impls you wrote by hand, at compile time. It adds nothing at runtime, and its types do not appear in your public API. Callers see a normal enum that implements std::error::Error.
cargo add thiserrorYou derive Error next to Debug. Debug is still required, because Error has Debug as a supertrait. Then you put an #[error("...")] attribute on each variant.
use thiserror::Error;
#[derive(Debug, Error)]
pub enum ConfigError {
#[error("missing key: {0}")]
Missing(String),
#[error("port {port} is out of range ({min}-{max})")]
PortRange { port: u32, min: u16, max: u16 },
#[error("config file is empty")]
Empty,
}
pub fn check_port(port: u32) -> Result<u16, ConfigError> {
u16::try_from(port)
.ok()
.filter(|p| *p != 0)
.ok_or(ConfigError::PortRange { port, min: 1, max: u16::MAX })
}
fn main() {
for input in [8080, 0, 70000] {
match check_port(input) {
Ok(p) => println!("ok: {p}"),
Err(e) => println!("error: {e}"),
}
}
println!("{}", ConfigError::Missing("host".into()));
println!("{}", ConfigError::Empty);
}Running it prints ok: 8080, then the two out-of-range messages, then missing key: host and config file is empty.
What the derive generates
The Display impl is a match over your variants, and each arm calls write! with your format string. The Error impl is empty unless you mark a source, which the next chapter covers.
Writing the format strings
The string in #[error(...)] works like a format! string, with field access added.
| Variant shape | Reference fields with | Example |
|---|---|---|
| Tuple | `{0}`, `{1}` | `#[error("missing key: {0}")]` |
| Struct-like | `{name}` | `#[error("port {port} is bad")]` |
| Unit | nothing to reference | `#[error("config file is empty")]` |
You can use format specs such as {0:?} for Debug output. You can also pass extra arguments that start with a dot. Here .0 means "field 0 of this variant":
use thiserror::Error;
#[derive(Debug, Error)]
pub enum NameError {
#[error("name too long: {} bytes (max {})", .0.len(), 32)]
TooLong(String),
}Rules to keep in mind
- Every variant needs an
#[error(...)]attribute, or you must use#[error(transparent)], which forwardsDisplayto the wrapped error. Otherwise the derive fails to compile. - A field named
source, or one marked#[source]or#[from], is treated as the error's cause. The next chapter explains how. - Keep messages lowercase and without a trailing period. Reporting code often joins several messages with
:. - Do not repeat the source error's text in your own message. It already appears when the chain is printed.
Exercise
A variant is declared as #[error("bad value {value} for {key}")] BadValue { key: String, value: i64 }. What does ConfigError::BadValue { key: "retries".into(), value: -1 }.to_string() return? What compile error do you get if you remove the #[error] attribute from the variant?
Show answer
It returns "bad value -1 for retries". Without the attribute the derive fails, because thiserror requires an #[error(...)] attribute (or #[error(transparent)]) on every variant so it can generate Display.