Sub topic 13
Designing error types that age well
An error type is part of your API. Callers match on it, tests assert on it, and logs print it. Changing it later can break other people's code. This chapter covers how to shape error types so that they survive new features, new dependencies, and new callers.
It assumes you have read the earlier chapters. You should know thiserror (#[error], #[from], #[source]), anyhow with Context, and the library-versus-application split. It also assumes you understand how ? converts errors through From.
What "aging well" means
An error type ages well when you can make the following changes without a major version bump:
- Add a new failure case.
- Replace the crate you use internally.
- Add more detail to an existing case.
- Reword a message.
Most of the practices below protect one of these four changes.
Design variants around what the caller can do
Name variants after what the caller can do about the failure, not after where in your code it happened. A variant like FailedInsideParser helps nobody. A caller can act on NotFound, PermissionDenied, or InvalidInput. They can retry, show a message, or fix the input.
A good test is to ask what code would match on this variant. If you can't imagine any, the variant probably belongs in the Display text or the source, not in the enum.
| Approach | Example variants | Caller experience |
|---|---|---|
| By origin | `Io`, `Json`, `Http` | The caller must know your internals to react. |
| By cause the caller cares about | `NotFound`, `Unauthorized`, `Malformed` | The caller reacts without knowing your internals. |
Origin-based enums are fine for small private modules, where they are quick to write. Prefer outcome-based variants at public boundaries.
Make the enum extensible with `#[non_exhaustive]`
Adding a variant to a public enum breaks every downstream match that lists all the variants. Mark public error enums #[non_exhaustive], and downstream crates must include a wildcard arm. You can then add variants in a minor release.
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(e: &ConfigError) -> &'static str {
match e {
ConfigError::Missing(_) => "missing",
ConfigError::InvalidPort(_) => "bad port",
// Required in other crates. Inside this crate it only triggers
// an "unreachable pattern" warning.
#[allow(unreachable_patterns)]
_ => "other",
}
}The attribute also works on a single variant that has named fields. That lets you add fields to the variant later without breaking code that builds or destructures it.
The trade-off is that callers lose exhaustiveness checking. When you add a variant, their compiler no longer points out the places that need review. For error enums that is usually the right price, because new failure modes are a normal part of a library's life.
Don't leak dependency types
Consider this variant:
Http(#[from] some_http_crate::Error)It makes some_http_crate part of your public API. If you upgrade it to a new major version, your own error type changes, so you must also release a new major version. Callers can also start matching on the dependency's types, which locks you into that crate.
There are two common fixes.
Box the source. Keep the cause for reporting, but hide its type:
use std::error::Error;
use thiserror::Error;
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum FetchError {
#[error("network request failed")]
Network(#[source] Box<dyn Error + Send + Sync>),
#[error("response was not valid")]
BadResponse,
}
fn network<E>(e: E) -> FetchError
where
E: Error + Send + Sync + 'static,
{
FetchError::Network(Box::new(e))
}Use .map_err(network)? at call sites. The cause still appears in source() chains, so error reports show it. Callers can still reach it with downcast_ref if they choose to, but your signature promises nothing.
Use an opaque struct. This hides the whole enum, as the next section shows.
Dropping #[from] for third-party types also has a second benefit. A blanket From impl converts every error of that type the same way, so you lose the chance to attach context such as a path or a URL.
Opaque errors: hide the representation
If you expect the set of failure kinds to change often, expose a struct with a private field and public query methods:
use std::num::ParseIntError;
use thiserror::Error;
#[derive(Debug, Error)]
enum Kind {
#[error("input is empty")]
Empty,
#[error("not a number")]
BadNumber(#[source] ParseIntError),
}
#[derive(Debug, Error)]
#[error(transparent)]
pub struct ParseError {
kind: Kind,
}
impl ParseError {
pub fn is_empty_input(&self) -> bool {
matches!(self.kind, Kind::Empty)
}
}
pub fn parse_count(s: &str) -> Result<u32, ParseError> {
let s = s.trim();
if s.is_empty() {
return Err(ParseError { kind: Kind::Empty });
}
s.parse()
.map_err(|e| ParseError { kind: Kind::BadNumber(e) })
}
fn main() {
for input in ["42", " ", "abc"] {
match parse_count(input) {
Ok(n) => println!("{input:?} -> {n}"),
Err(e) if e.is_empty_input() => println!("{input:?} -> nothing to parse"),
Err(e) => println!("{input:?} -> error: {e}"),
}
}
}#[error(transparent)] forwards Display and source() to the inner Kind. You can now add, rename, or remove Kind variants freely. Only the public methods are promised.
The cost is more code and less discoverability. Callers can't match, so you must anticipate which questions they will ask and provide a method for each. Use this style when stability matters more than convenience. The standard library's std::io::Error takes a similar approach with kind().
The diagram summarizes the decision for a public error type.
Carry data, not pre-formatted text
A variant should hold the facts, and Display should assemble them into a message. Read { path, source } is better than Read(String) holding "could not read config.toml". With the structured form, a caller can use the path programmatically, and you can change the wording later without breaking anyone's logic.
Never ask callers to parse your message text. If someone ends up matching on e.to_string().contains("not found"), your error type is missing a variant or a method.
Keep `Display` and `source()` separate
An error should describe only its own level. The cause belongs in source(). If you put the cause in both places, reporters that walk the chain print it twice:
could not read config.toml: permission denied: permission deniedApply the following conventions for messages:
- Start with a lowercase letter.
- Omit the trailing period.
- Describe what failed, not what to do next.
- Leave the source's text out of the message.
These conventions let reporters join levels with : and produce readable one-line output. The chain-walking from the earlier reporting chapter then works well for every error you design.
Make errors `Send + Sync + 'static`
anyhow::Error can only wrap types that are Send + Sync + 'static. Errors also cross thread boundaries in async runtimes and thread pools. Avoid fields like Rc<T>, RefCell<T>, or borrowed &str in an error. Own your data with String or PathBuf. A borrowed field also stops the error from outliving the input that caused it, which makes ? awkward in longer call chains.
When you add a boxed source, write Box<dyn Error + Send + Sync>, not a bare Box<dyn Error>. The bare form is not Send or Sync, so it won't convert into anyhow::Error.
One error type per boundary, not per program
A single giant Error enum for a whole crate tends to grow variants that no single function can return. Every caller then has to handle cases that are impossible for the function they called. When operations fail in different ways, give them separate types:
ParseErrorforparse_config.ConnectErrorforconnect.
Then compose them in a higher-level type only where a function really combines both, using #[from] for the plain wrappers. This keeps each signature honest: the type shows exactly what can go wrong.
Don't go to the other extreme, with a new type for every function. Group operations that fail for the same reasons.
Review checklist
Before you publish a public error type, check:
- Variants name outcomes a caller can act on.
- The enum is
#[non_exhaustive], or the type is an opaque struct. - No third-party error type appears in the public signature.
- Variants hold data, and
Displayformats it. Displayleaves out the source text.- The type is
Send + Sync + 'static. - A test pins the variant for each documented failure, as in the earlier testing chapter.
Exercise
A library error enum has the variant Http(#[from] reqwest::Error). Name two problems with this for a published library, and give a fix for each.
Show answer
First, the dependency becomes part of the public API. A major upgrade of that crate forces a breaking release of yours, and callers can couple their code to it. Fix it by boxing the source as Box<dyn Error + Send + Sync> or by hiding the enum behind an opaque struct. Second, #[from] converts every such error the same way, so you can't attach context like the URL. Fix it by dropping #[from] and building the variant with map_err, with a field for the URL.
Exercise
You add a new variant Timeout to a public enum. Callers' code stops compiling. What should you have done earlier, and what must callers write after that change?
Show answer
Mark the enum #[non_exhaustive] before the first release. Callers in other crates then must include a wildcard arm (_ => ...) in every match, so adding Timeout later compiles in their code and is not a breaking change.
Exercise
Why does the message could not read config.toml: permission denied: permission denied appear, and how do you stop it?
Show answer
The error's Display includes the source's text, and the chain reporter also prints the source as the next level. Remove the source's text from Display (write could not read {path}) and keep the cause only in source(), for example with #[source].