thiserror crate
Learn what the thiserror crate is, how to add it as a dependency, and when it helps an Axum app write error types
thiserror is a small Rust crate that writes the boring parts of an error type for you. You describe each error variant with a short message, and thiserror generates the Display implementation and the std::error::Error implementation that the message implies. It does not change what your errors mean, it does not change the JSON your app returns, and it does not appear in your public API. It only removes the repetitive code you would otherwise write by hand.
Where This Fits
The page about the JSON error body finished the hand-written version of the error design: the enum, the response conversion, the status mapping, and the body shape. Everything works, and everything is written by hand. This page introduces the crate that takes over one repetitive piece of that hand-written code, the part that turns each variant into a human readable message. The enum stays the same, the messages stay the same, and the code that produces them gets shorter.
Think of a stencil. You could draw the same letter by hand fifty times, and each copy would take the same care. Or you could cut the letter once and trace it fifty times, and each copy would match. thiserror is the stencil for error messages: you cut the message once, and the crate traces the implementation for you.
The Smallest Working Version
Add the crate to Cargo.toml first, then use it. The dependency line goes with the others, and the version follows the style the rest of the project uses.
[package]
name = "axum-project"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
thiserror = "2.0"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
[dev-dependencies]
tower = { version = "0.5", features = ["util"] }
thiserror = "2.0" asks for version 2.0.21, the current release in the 2.x line, and lets Cargo pick the latest patch release that still starts with 2.0. The 2.0 form matches the style the project already uses for axum = "0.8" and serde_json = "1", where only the leading version is pinned and patch updates come in automatically. Run cargo build after adding the line, and Cargo downloads the crate and compiles it. The build output ends with a Finished line, and there is nothing else to configure.
A Dependency Is a Line in Cargo.toml:
Adding a crate means adding one line under [dependencies] and building once. There is no config file, no feature flag to enable for basic use, and no setup function to call. If cargo build succeeds, the crate is ready to use.
What thiserror Is
thiserror provides a derive macro, a piece of code that runs at compile time and writes Rust code for you. A derive macro reads the type you attached it to and generates implementations based on what it finds there. In this case, the macro is called Error, and it generates two implementations: Display, which turns the error into a human readable string, and std::error::Error, which marks the type as an error in the standard library sense.
Display is the trait behind the {} format placeholder, the one used in println!("{}", error) and in error.to_string(). std::error::Error is the trait behind error handling in the standard library: it requires Debug and Display, and it provides the source() method, which returns the underlying cause of an error when there is one. Together, the two traits make a type behave like a proper Rust error, printable and chainable, and thiserror writes both from the short annotations you put on the variants.
The crate is a proc-macro crate, which means its code runs during compilation and produces no runtime code of its own. There is no thiserror object in your running program, no runtime cost for using it, and no trace of it in the compiled binary beyond the implementations it generated. The generated code is exactly the code you would have written by hand, and switching from hand-written implementations to thiserror, or back again, is not a breaking change, because the resulting type behaves identically either way. That guarantee comes from the crate's own documentation, and it is the reason the crate is safe to adopt in the middle of a project.
What thiserror Does Not Do
The crate does one job, and the list of things it does not do is as important as the job itself. It does not generate the IntoResponse implementation, so your Axum error responses still come from the hand-written block in errors.rs. It does not choose status codes, and it does not build JSON bodies. It does not validate input, and it does not decide which variant a handler returns. It only writes the Display and Error implementations for the enum you annotate.
It also does not appear in your public API. A caller of your library sees an error type with a Display implementation and an Error implementation, and cannot tell whether those were written by hand or generated. That matters because it means adopting the crate is a private decision: it changes your source code, not your interface, and removing it later changes nothing for anyone who uses your code.
thiserror Writes Messages, Not Responses:
A common beginner mistake is expecting thiserror to handle the HTTP side of errors. It never touches HTTP. The status code, the JSON body, and the content type all still come from the IntoResponse implementation, and that implementation is unchanged by adding this crate.
The Hand-Written Code It Replaces
To see what the crate saves, look at the code it replaces. A hand-written Display implementation for the shared enum is a match with one arm per variant, and each arm writes the message for that variant.
use std::fmt;
#[derive(Debug)]
pub enum AppError {
NotFound,
ValidationError(String),
InternalError,
}
impl fmt::Display for AppError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
AppError::NotFound => write!(f, "resource not found"),
AppError::ValidationError(message) => write!(f, "{message}"),
AppError::InternalError => write!(f, "something went wrong"),
}
}
}
impl std::error::Error for AppError {}
fmt::Display requires a fmt method that writes the human readable form into a formatter, and write! is the macro that does the writing. The ValidationError arm writes the inner message with {message}, which interpolates the variable into the format string. The std::error::Error implementation is empty, because the trait's methods all have defaults, and the empty block is enough to mark the type as an error. This code compiles, it runs, and it is correct. It is also the same shape for every error enum in every Rust project, which is why generating it is worth a crate.
A scratch test compared this hand-written version against the thiserror version, asserting that both print exactly the same strings for all three variants, and it passed. The two forms are interchangeable in behaviour. The difference is only in how much code you maintain.
When thiserror Helps
The crate helps most when the enum has several variants and each one needs its own message. Three variants with a hand-written Display is a short match, and the saving is small. Ten variants is a long match, and every new variant means a new arm written by hand, a new chance to mistype a message, and a new place where the message and the variant can drift apart. With thiserror, a new variant is one line for the variant and one annotation for its message, and the implementation follows automatically.
It also helps when the messages interpolate values. A variant like ValidationError(String) needs its message written into the output, and the hand-written arm does that with a write! call and a format placeholder. The thiserror annotation does the same with "{0}", which is shorter and harder to get wrong. The next page covers the annotations in detail, including that placeholder.
The crate helps least when the enum has one variant, or when the error type is thrown away after one use. A single-variant enum needs a three-line Display implementation, and adding a dependency to save three lines is not worth it. A prototype that will be rewritten tomorrow does not need it either. The rule is practical: if the hand-written implementation is getting long enough to be annoying, the crate earns its place. If it is short enough to read at a glance, it does not.
When to Skip It
Not every project needs the crate, and knowing when to skip it is part of knowing when to use it. A tiny enum with one or two variants and fixed messages is clearer hand-written, because the reader sees the whole implementation in one glance without learning a new annotation. A project that already has a hand-written implementation that works does not need to be rewritten, because the rewrite changes nothing the user can see. A codebase with strict dependency rules may prefer zero extra crates, and the hand-written form costs nothing but lines.
The crate is also the wrong tool for unstructured errors. If the app needs a single error type that can hold any message, with no variants to match on, the anyhow crate fits that job better, because it is built for opaque errors that are only ever displayed. thiserror is for structured errors, enums whose variants callers match on, and AppError is exactly that shape: three variants, each with its own meaning, each matched on by the response code.
Adding the Crate Step by Step
Adding a dependency is a short sequence, and the order matters: edit the file, build, and check the lockfile. The steps below use the manual edit, which is the form this project uses for every dependency.
Step 1: Add the dependency line
Open Cargo.toml and add thiserror = "2.0" under [dependencies], next to the other crates. Save the file.
[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
thiserror = "2.0"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
Step 2: Build the project
Run cargo build in the project directory. Cargo downloads thiserror 2.0.21 and its companion macro crate, thiserror-impl, which holds the derive macro itself, compiles them, and records the exact versions in Cargo.lock. The two crates are the whole dependency: the small runtime crate and the macro crate that generates code from your annotations.
cargo build
Step 3: Check the build finished
The output ends with a Finished line and no errors. The crate is now available to import with use thiserror::Error; in any file.
Finished `dev` profile [unoptimized + debuginfo] target(s)
Cargo.lock is the file that records the exact version Cargo chose, 2.0.21, along with the exact versions of every other dependency. It is generated by Cargo, and it is committed to version control, so every developer and every build uses the same versions. You never edit it by hand. If the build fails with a network error, the lockfile is the first thing to check, because a stale lock entry is the usual cause.
Migrating an Existing Hand-Written Enum
Adopting the crate in a project that already has a hand-written Display implementation is a short, safe migration, because the behaviour is identical on both sides of it. The steps below are the whole job, and the tests are what prove each step.
Step 1: Add the dependency and build
Add thiserror = "2.0" to Cargo.toml and run cargo build. The project still uses the hand-written implementation at this point, so nothing about the running program changes.
cargo build
Step 2: Add the derive and the annotations
Replace the hand-written Display and Error implementations with #[derive(Error, Debug)] and one #[error("...")] per variant. The messages in the annotations must match the strings the hand-written arms wrote, word for word.
Step 3: Run the tests
Run cargo test. The tests that assert the exact JSON bodies and the tests that print the errors must all pass unchanged, because the messages are the same. A test that fails here means an annotation differs from the arm it replaced, and the test output shows the two strings side by side.
cargo test
A Clean Migration:
If cargo test passes with no test file changed, the migration is complete. The same messages, the same statuses, and the same bodies, with the hand-written implementation gone. That is the whole point of the crate: less code, identical behaviour.
How the Crate Fits the AppError Design
The enum, the response conversion, and the status mapping all stay exactly as they are. The crate touches one thing: the messages. The hand-written Display implementation is replaced by annotations on the variants, and the IntoResponse implementation keeps working, because it never used Display in the first place. The response conversion matches on variants and builds messages from fixed strings and the carried String, not from the Display output.
That separation is what makes the adoption safe. The change is local to src/errors.rs, it affects no handler, no route, and no test that checks statuses and bodies. The tests that assert the exact JSON bodies keep passing, because the bodies are built from the same messages by the same code. The only tests that change are ones that print the error with {} or call .to_string() on it, and those start passing with the same strings, because the generated Display prints the same messages the hand-written one did.
How Errors Flow With thiserror
The flow below shows where the crate sits in the design. It is a compile-time step, not a runtime step, and it never appears in the request path.
Developer writes #[derive(Error)] and #[error("...")] on AppError
|
v
Compiler runs the thiserror macro while building
|
v
Macro generates Display and std::error::Error implementations
|
v
Running program uses the generated code like hand-written code
|
v
Handlers, IntoResponse, statuses, and JSON bodies are unchanged
The request path is the bottom two lines, and the crate is nowhere in it. A request arrives, a handler returns a variant, the response conversion builds the body, and the client receives it. The macro did its work hours earlier, at compile time, and the running server never knows it was involved.
Testing That the Crate Is Set Up
The test below proves the crate is available and that the generated code behaves like the hand-written code it replaces. It defines a small error enum with the derive, prints each variant, and compares the output with the hand-written version.
use std::fmt;
use thiserror::Error;
#[derive(Error, Debug)]
enum DerivedError {
#[error("resource not found")]
NotFound,
#[error("{0}")]
ValidationError(String),
#[error("something went wrong")]
InternalError,
}
#[derive(Debug)]
enum ManualError {
NotFound,
ValidationError(String),
InternalError,
}
impl fmt::Display for ManualError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ManualError::NotFound => write!(f, "resource not found"),
ManualError::ValidationError(message) => write!(f, "{message}"),
ManualError::InternalError => write!(f, "something went wrong"),
}
}
}
impl std::error::Error for ManualError {}
#[test]
fn derived_display_matches_handwritten_display() {
assert_eq!(
ManualError::NotFound.to_string(),
DerivedError::NotFound.to_string()
);
assert_eq!(
ManualError::ValidationError("title must not be empty".to_string()).to_string(),
DerivedError::ValidationError("title must not be empty".to_string()).to_string()
);
assert_eq!(
ManualError::InternalError.to_string(),
DerivedError::InternalError.to_string()
);
}
#[test]
fn derived_error_implements_std_error() {
let err: &dyn std::error::Error = &DerivedError::NotFound;
assert!(err.source().is_none());
}
The first test asserts that the derived Display prints the same strings as the hand-written one, for all three variants. The second test proves the type implements std::error::Error, by treating it as a trait object and calling source(), which returns None because none of the variants wraps an underlying error. Both tests passed against the scratch project with thiserror 2.0.21. Run them with cargo test and expect:
test derived_display_matches_handwritten_display ... ok
test derived_error_implements_std_error ... ok
The #[derive(Error, Debug)] line is the whole usage in this test, and the next page explains each piece of it. The use thiserror::Error; import brings the derive macro into scope, and use std::fmt; brings the formatting module in for the hand-written comparison.
Common Beginner Mistakes
Expecting thiserror to build the HTTP response
// Wrong - the derive writes Display, not IntoResponse
use thiserror::Error;
#[derive(Error, Debug)]
pub enum AppError {
#[error("resource not found")]
NotFound,
#[error("{0}")]
ValidationError(String),
#[error("something went wrong")]
InternalError,
}
// Wrong - this handler still does not compile without the impl
async fn get_book(Path(id): Path<u32>) -> Result<Json<Book>, AppError> {
Err(AppError::NotFound)
}
The derive macro generates Display and std::error::Error, and nothing else. A handler returning Result<Json<Book>, AppError> still needs the impl IntoResponse for AppError block, because Axum turns errors into responses through that trait, not through Display. The fix is to keep the implementation in errors.rs alongside the derived enum. The two pieces are independent: the derive writes messages, the impl writes responses.
Two Traits, Two Jobs:
Display turns an error into a string for humans. IntoResponse turns an error into an HTTP response for clients. The derive provides the first, and only the first. If the compiler says AppError does not implement IntoResponse, the derive is not the fix, the impl block is.
Adding the dependency but forgetting to build
# Added to Cargo.toml, but cargo build was never run
[dependencies]
thiserror = "2.0"
// Wrong - the compiler cannot find the crate yet
use thiserror::Error;
The use line fails with an "unresolved import" error until Cargo has downloaded and compiled the crate, which happens on the next build. The fix is cargo build after editing Cargo.toml. The error message names the missing crate, which is the compiler telling you the download step has not happened yet.
Pinning the wrong major version
# Wrong - version 1 has a different derive and different behaviour
thiserror = "1"
Version 1 of thiserror exists and is widely used, but this project uses version 2, and the two versions differ in details that matter, including the minimum Rust version and some attribute behaviour. The Cargo.toml line in this project is thiserror = "2.0", which selects the 2.x line and the current 2.0.21 release. Copy the line from this page, do not guess the version, and check the lockfile if the build picks something unexpected.
Reaching for thiserror for a one-variant error
// Unnecessary - a single fixed message needs no macro
use thiserror::Error;
#[derive(Error, Debug)]
pub enum SingleError {
#[error("something went wrong")]
Failed,
}
This compiles and works, and it is more machinery than the problem deserves. A one-variant enum needs a three-line hand-written Display, and the derive adds a dependency, an import, and an annotation to save those three lines. The crate earns its place when the enum grows, not when it is born. Start hand-written, and adopt the crate when the match gets long enough to be annoying.
Final Complete Example
Here is everything from this page in one place: the Cargo.toml with the new dependency, the hand-written Display the crate replaces, and the test that proves the two forms print the same strings.
[package]
name = "axum-project"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
thiserror = "2.0"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
[dev-dependencies]
tower = { version = "0.5", features = ["util"] }
use std::fmt;
#[derive(Debug)]
pub enum AppError {
NotFound,
ValidationError(String),
InternalError,
}
impl fmt::Display for AppError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
AppError::NotFound => write!(f, "resource not found"),
AppError::ValidationError(message) => write!(f, "{message}"),
AppError::InternalError => write!(f, "something went wrong"),
}
}
}
impl std::error::Error for AppError {}
Run cargo build after adding the dependency line, then run cargo test, and the two setup tests pass. The hand-written implementation above is the last time it appears in this design: the next page replaces it with the derive.
Summary
thiserror is a small, honest trade: one dependency line in exchange for never writing a repetitive Display implementation by hand again. The decision framework is a count of variants and messages. When the enum is small and the messages are fixed, write the implementation by hand and skip the crate. When the enum grows, when messages interpolate values, and when every new variant means another arm in a match you have written before, add the crate and let the macro write the repetitive part. The deeper point is that the crate changes nothing the user can see. The enum keeps its variants, the responses keep their statuses and bodies, and the only thing that changes is how many lines you maintain. A dependency that buys you less code without changing behaviour is a dependency worth having, and a dependency that changes behaviour without buying you less code is one to leave alone.