Sub topic 13
Designing error types that age well
This chapter assumes you can write a thiserror enum, use #[from] and #[source], and know when a library should use thiserror and an application anyhow. The focus here is how to keep an error type usable as the crate grows and as other code starts to depend on it.
Why error types are hard to change
A public error enum is part of your API. Callers match on its variants, so these changes break their code:
- Adding a variant, because their
matchis no longer exhaustive. - Removing or renaming a variant.
- Changing the type inside a variant, such as swapping one crate's error for another.
Design the type so that you can make these changes later without a major version bump.
Mark public enums as non-exhaustive
#[non_exhaustive] forces callers outside your crate to include a wildcard arm. You can then add variants freely.
use thiserror::Error;
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum ConfigError {
#[error("missing key: {0}")]
Missing(String),
#[error("invalid port")]
InvalidPort(#[from] std::num::ParseIntError),
}
pub fn describe(err: &ConfigError) -> &'static str {
match err {
ConfigError::Missing(_) => "add the key",
ConfigError::InvalidPort(_) => "use a number from 0 to 65535",
_ => "see the error message",
}
}Inside your own crate the wildcard arm is optional. Outside it, the compiler requires one.
Do not leak dependency types
A variant such as Parse(#[from] serde_json::Error) makes serde_json part of your public API. Upgrading that dependency across a breaking release then forces a breaking release of your crate too.
Wrap the cause so that callers only see std types:
use thiserror::Error;
#[derive(Debug, Error)]
pub enum LoadError {
#[error("config file is malformed")]
Malformed(#[source] Box<dyn std::error::Error + Send + Sync>),
#[error("could not read {path}")]
Read {
path: String,
#[source]
source: std::io::Error,
},
}Callers can still walk the source chain and print the cause. They cannot match on the dependency's type. Use Send + Sync on boxed causes so the error can cross thread boundaries.
Write messages for the chain
The Display text should describe only this layer. The cause belongs in source(), and reporters print it as the next line of the chain.
| Practice | Avoid | Prefer |
|---|---|---|
| Case and punctuation | `Invalid port.` | `invalid port` |
| Cause in message | `"read failed: {source}"` | `"could not read {path}"` with `#[source]` |
| Useful data | `"missing key"` | `"missing key: {0}"` |
If a message includes its source, the cause prints twice in a chain report.
Make variants match caller decisions
Add a variant when a caller would act differently on it. A missing file might trigger a default config, while a malformed file should stop the program. Those are two variants. Ten different I/O failure points that all lead to "give up" can share one Read variant.
Keep these habits:
- Put in each variant the data a caller needs to react, such as the path or the key.
- Split a large crate-wide enum into one error type per module or operation. A function should not return a variant it can never produce.
- Keep
#[error(transparent)]for variants that only forward another error. It copies bothDisplayandsourcefrom the inner error.
Deciding what to expose
Common mistakes
- Deriving
PartialEqon an error that holdsstd::io::Error. It does not implementPartialEq, so test withmatches!instead. - Adding
#[from]on two variants with the same inner type. The secondFromimpl conflicts with the first, so usemap_errto pick the variant. - Using
Stringas the only payload. Callers then have to parse text to learn what went wrong.
Exercise
A library's public error has the variant Http(#[from] reqwest::Error). Name two problems this causes, and give one fix.
Show answer
It exposes reqwest in the public API, so a breaking upgrade of reqwest forces a breaking release of your crate. Callers can also match on a type they may not otherwise depend on. Fix it by wrapping the cause as Http(#[source] Box<dyn std::error::Error + Send + Sync>), or by defining your own small error type with a #[source] field. Adding #[non_exhaustive] to the enum also lets you add variants later.