Sub topic 4
Removing the boilerplate with thiserror
This chapter assumes you can read Rust enums and pattern matching, you know Result and the ? operator, and you have seen the hand-written error type from the previous chapter. You should also be comfortable with #[derive(...)] and with adding a crate using Cargo.
The cost of writing errors by hand
A hand-written error enum needs four separate pieces before it works well with ?:
#[derive(Debug)]on the type.- An
impl fmt::Displaythat writes a message for each variant. - An
impl std::error::Error, with asourcemethod if the error wraps another one. - One
impl From<...>for each error type you want?to convert automatically.
None of this is hard, but it is repetitive. Every new variant means editing the Display match, possibly the source match, and possibly adding another From impl. Forgetting one produces either a compile error or, worse, a message that is quietly wrong.
thiserror is a derive macro crate that generates these implementations from attributes you place on the type. It writes the same code you would write by hand. It adds no runtime cost and nothing from thiserror appears in your public API. Callers see an ordinary type that implements std::error::Error.
Adding the crate
cargo add thiserror anyhowA library crate would normally add only thiserror. This chapter uses only thiserror. The anyhow crate is covered in later chapters.
The same error, rewritten
Here is the ConfigError type from the manual version, plus a third variant, written with thiserror.
use thiserror::Error;
#[derive(Debug, Error)]
pub enum ConfigError {
#[error("missing key: {0}")]
Missing(String),
#[error("invalid port")]
InvalidPort(#[from] std::num::ParseIntError),
#[error("could not read {path}")]
Read {
path: String,
#[source]
source: std::io::Error,
},
}
pub fn parse_port(s: &str) -> Result<u16, ConfigError> {
Ok(s.trim().parse::<u16>()?)
}
pub fn read_config(path: &str) -> Result<String, ConfigError> {
std::fs::read_to_string(path).map_err(|source| ConfigError::Read {
path: path.to_string(),
source,
})
}The enum derives Debug itself, because thiserror does not derive it for you. The Error derive then generates three things:
impl Display, using the#[error("...")]string on each variant.impl std::error::Error, including asourcemethod.impl From<ParseIntError> for ConfigError, because of#[from].
The ? in parse_port works exactly as it did in the manual version. The compiler finds the generated From impl and converts the ParseIntError into ConfigError::InvalidPort.
The #[error] attribute
#[error("...")] takes a format string, as write! does. How you refer to fields depends on the variant's shape.
| Variant shape | Example | How to refer to fields |
|---|---|---|
| Tuple | `Missing(String)` | `{0}`, `{1}`, and so on |
| Struct | `Read { path, source }` | `{path}`, `{source}` |
| Unit | `Timeout` | No fields to refer to |
Inside the string you can also format with the usual specifiers, such as {0:?} for the Debug form or {count:>4}. You can also pass extra expressions after the string, and a leading dot refers to a field:
use thiserror::Error;
#[derive(Debug, Error)]
pub enum LimitError {
#[error("value {value} is above the limit of {}", .limit)]
TooLarge { value: u32, limit: u32 },
#[error("expected {expected} items, found {}", .found.len())]
WrongCount { expected: usize, found: Vec<String> },
}
fn main() {
let e = LimitError::TooLarge { value: 12, limit: 10 };
println!("{e}");
let e = LimitError::WrongCount {
expected: 3,
found: vec!["a".to_string()],
};
println!("{e}");
}Running this prints:
value 12 is above the limit of 10
expected 3 items, found 1The .found.len() form lets you compute a value for the message without storing it as a separate field.
Transparent forwarding
Sometimes a variant should add no message of its own. Use #[error(transparent)] and the variant forwards both Display and source to the inner error:
use thiserror::Error;
#[derive(Debug, Error)]
pub enum AppError {
#[error("bad configuration")]
Config(#[from] ConfigError),
#[error(transparent)]
Other(#[from] std::io::Error),
}
#[derive(Debug, Error)]
pub enum ConfigError {
#[error("missing key: {0}")]
Missing(String),
}A transparent variant must have exactly one field. It is useful for a catch-all variant, or when you want to hide that a wrapper type exists.
How #[from] and #[source] differ
Both attributes mark a field as the underlying cause. They differ in what else they generate.
| Attribute | Generates `source()` | Generates `From` | Other fields allowed |
|---|---|---|---|
| `#[source]` | Yes | No | Yes |
| `#[from]` | Yes | Yes | No |
A field named source is treated as the source automatically, so #[source] is optional on it. In the Read variant above it is written out for clarity.
The restriction on #[from] follows from how From works. From<io::Error> for ConfigError takes only an io::Error. If the variant also stored a path, the macro could not invent a value for it. That is why Read uses #[source] and a map_err call. You build the variant by hand, supplying the path yourself.
The same logic gives a second restriction: you cannot have two variants with #[from] on the same source type. The compiler would find two conflicting From impls. If two operations can both fail with io::Error, use #[source] in both variants and build each one explicitly. That also lets each variant say which operation failed.
Generic and borrowed fields
The derive works with generics and with fields of any type, as long as the formatting you ask for is valid. A #[source] field must implement std::error::Error + 'static, or be a Box<dyn Error + Send + Sync + 'static>. This is a frequent source of compile errors:
use thiserror::Error;
#[derive(Debug, Error)]
pub enum PluginError {
#[error("plugin {name} failed")]
Failed {
name: String,
#[source]
cause: Box<dyn std::error::Error + Send + Sync + 'static>,
},
}The Send + Sync bounds are not required by thiserror. They matter because errors often cross thread boundaries, for example in async runtimes, and a plain Box<dyn Error> would make your error type unusable there.
Common errors
These mistakes come up repeatedly when people first use thiserror.
- Forgetting
#[derive(Debug)]. The error isErrorrequiresDebug, and the derive does not add it. The compiler reports thatDebugis not implemented. - A missing
#[error]message. Every variant needs one, unless the variant is#[error(transparent)]. Leaving it off gives a compile error pointing at the variant. #[from]with extra fields. A variant with#[from]can hold only that one field, apart from an optional backtrace. Switch to#[source]andmap_err.- Duplicate
#[from]types. Two variants cannot convert from the same type. Pick one to keep#[from], and build the other by hand. - Printing only the top-level message.
{}on the outer error shows only that variant's#[error]text. If you want the cause, you must walksource(), which a later chapter covers. - Repeating the source in the message. Writing
#[error("invalid port: {0}")]on a variant that also has#[from]means that a reporter that walks the chain prints the inner message twice. Keep the message about this level only.
What the macro actually generates
It helps to know that nothing magical happens. For the InvalidPort variant, the derive produces code roughly equal to this:
use std::fmt;
use std::num::ParseIntError;
#[derive(Debug)]
pub enum ConfigError {
InvalidPort(ParseIntError),
}
impl fmt::Display for ConfigError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ConfigError::InvalidPort(_) => write!(f, "invalid port"),
}
}
}
impl std::error::Error for ConfigError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
ConfigError::InvalidPort(e) => Some(e),
}
}
}
impl From<ParseIntError> for ConfigError {
fn from(e: ParseIntError) -> Self {
ConfigError::InvalidPort(e)
}
}That is the same code as the manual version. If a thiserror error ever behaves unexpectedly, you can reason about it by writing out this expansion. The cargo expand tool will print the real output for your own types.
Practice
Exercise
A variant is declared as Read { path: String, #[from] source: std::io::Error }. It does not compile. Explain why, and show the fix that keeps the path in the error.
Show answer
#[from] generates impl From<std::io::Error> for ConfigError, which receives only an io::Error. The macro cannot supply a value for path, so a variant with #[from] may not carry other fields. Change #[from] to #[source] and construct the variant yourself: std::fs::read_to_string(path).map_err(|source| ConfigError::Read { path: path.to_string(), source }).
Exercise
You write two variants, Open(#[from] std::io::Error) and Write(#[from] std::io::Error). What goes wrong, and how do you keep both variants?
Show answer
Both derives generate impl From<std::io::Error> for ConfigError, so the compiler reports conflicting implementations. Keep #[from] on at most one variant, or use #[source] on both and build each with map_err, for example .map_err(ConfigError::Open) after changing the variant to a plain tuple field marked #[source]. Each variant then records which operation failed.