Composable Error Types with `thiserror` in Rust
`thiserror` generates boilerplate for custom Rust error types, letting you define specific, matchable errors for a library. Use it when callers need to handle different failure modes. The footgun is using it for simple app errors where `anyhow` would suffice.
WHY IT EXISTS Manually implementing std::error::Error, Display, and From for every custom error type is repetitive and error-prone. Rust's error handling philosophy encourages specific, typed errors, but this creates significant boilerplate for library authors who need to expose structured failure states to their users.
THE MENTAL MODEL Think of thiserror as a code generator for your error types. You define the what—the different error variants and their user-facing messages—in an enum, and thiserror handles the how by writing the impl Error, impl Display, and impl From blocks for you using simple attributes.
HOW IT WORKS You add #[derive(Error)] to an enum or struct. The #[error("...")] attribute on each variant generates the Display implementation, allowing you to format a message and interpolate fields with {field} syntax. The #[from] attribute on a field inside a variant automatically generates an impl From<SourceError> for YourError, allowing seamless conversion from an underlying error (like io::Error) into one of your enum variants. This also correctly sets up the source() method for error chaining, which is crucial for diagnostics.
WHEN TO USE IT Use thiserror when writing a library where consumers need to programmatically react to different kinds of errors. If a caller needs to distinguish between a network disconnect and a permissions error to decide whether to retry or fail fast, thiserror is the right tool. It helps you create a stable, public error API that users can match against.
WHEN NOT TO USE IT Avoid thiserror for top-level application error handling where you just need to propagate an error up the call stack and log it. For that, anyhow::Error is simpler, as it wraps any error type without requiring you to define a new enum for every possible failure. thiserror is for defining specific error types; anyhow is for handling them opaquely.
ONE CANONICAL EXAMPLE A data access library might define a DataStoreError enum. One variant, Disconnect(#[from] io::Error), could be generated automatically from an I/O error during a network call. Another, Redaction(String), could be a custom error for when a key is valid but the data is not available to the caller. A third, InvalidHeader { expected: String, found: String }, could be a struct variant with detailed diagnostic information. This lets a caller handle each case differently: retry on disconnect, log the redaction, or fail on an invalid header.
Read the original → docs.rs
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.