thiserror derive

Learn how derive Error and the error attribute rewrite AppError with per-variant Display messages and the same responses

The thiserror derive rewrites AppError so the messages are written once, on the variants themselves, instead of in a separate Display implementation. One line above the enum, #[derive(Error, Debug)], and one annotation per variant, #[error("...")], generate the Display and std::error::Error implementations the hand-written version spelled out in full. The enum keeps its variants, the responses keep their statuses and bodies, and the file gets shorter.

Where This Fits

The page about the thiserror crate introduced the dependency and showed the hand-written Display implementation it replaces. This page does the replacement. The crate is already in Cargo.toml, the hand-written implementation is still in src/errors.rs, and the derive takes its place. The enum does not change shape, the handlers do not change, and the responses do not change. Only the way the messages are produced changes.

Think of labels on jars. The hand-written version kept a separate list that said which label goes on which jar, and the list had to be checked every time a jar was added. The derive sticks the label on the jar itself, so the jar and its label can never drift apart. The annotation is the label, and the variant is the jar.

The Smallest Working Version

Replace the hand-written Display and Error implementations with the derive and one annotation per variant. The enum itself is unchanged.

src/errors.rs
use axum::{
    Json,
    http::StatusCode,
    response::{IntoResponse, Response},
};
use serde_json::json;
use thiserror::Error;

#[derive(Error, Debug)]
pub enum AppError {
    #[error("resource not found")]
    NotFound,
    #[error("{0}")]
    ValidationError(String),
    #[error("something went wrong")]
    InternalError,
}

impl IntoResponse for AppError {
    fn into_response(self) -> Response {
        let status = match &self {
            AppError::NotFound => StatusCode::NOT_FOUND,
            AppError::ValidationError(_) => StatusCode::UNPROCESSABLE_ENTITY,
            AppError::InternalError => StatusCode::INTERNAL_SERVER_ERROR,
        };
        let message = self.to_string();
        (status, Json(json!({ "error": message }))).into_response()
    }
}

The IntoResponse implementation changed in one place: the message now comes from self.to_string(), which uses the generated Display implementation, instead of from the match. The status still comes from a match, because the status is not a message and the derive does not generate it. The two decisions, which status and which message, now come from two different mechanisms, and each mechanism is the right one for its decision.

The Cargo.toml file needs the dependency from the crate page:

Cargo.toml
[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"] }

Run cargo build. The output ends with a Finished line, and the program behaves exactly as before. The handlers from the earlier pages are unchanged:

src/lib.rs
pub mod errors;

use axum::{
    Json,
    extract::Path,
    routing::{get, post},
    Router,
};
use errors::AppError;
use serde::{Deserialize, Serialize};

#[derive(Serialize)]
pub struct Book {
    pub id: u32,
    pub title: String,
}

#[derive(Deserialize)]
pub struct NewBook {
    pub title: String,
}

pub fn app() -> Router {
    Router::new()
        .route("/books/{id}", get(get_book))
        .route("/books", post(create_book))
        .route("/boom", get(boom))
}

async fn get_book(Path(id): Path<u32>) -> Result<Json<Book>, AppError> {
    if id == 1 {
        Ok(Json(Book {
            id: 1,
            title: "The Rust Book".to_string(),
        }))
    } else {
        Err(AppError::NotFound)
    }
}

async fn create_book(Json(input): Json<NewBook>) -> Result<Json<Book>, AppError> {
    if input.title.trim().is_empty() {
        return Err(AppError::ValidationError(
            "title must not be empty".to_string(),
        ));
    }
    Ok(Json(Book {
        id: 2,
        title: input.title,
    }))
}

async fn boom() -> Result<&'static str, AppError> {
    Err(AppError::InternalError)
}

Start the server and check all three failure paths:

curl -i http://127.0.0.1:3000/books/99
curl -i -X POST -H "content-type: application/json" -d '{"title":""}' http://127.0.0.1:3000/books
curl -i http://127.0.0.1:3000/boom

The responses are identical to the hand-written version:

HTTP/1.1 404 Not Found
{"error":"resource not found"}

HTTP/1.1 422 Unprocessable Entity
{"error":"title must not be empty"}

HTTP/1.1 500 Internal Server Error
{"error":"something went wrong"}

Nothing the client sees has changed. The derive changed how the messages are produced, not what they say, and the responses prove it.

Working Setup:

If the three curl commands return the same statuses and bodies as before the rewrite, the derive is working and the rewrite changed nothing the client can see.

Understanding the Derive Line by Line

The derive block is short, and each annotation in it has a precise meaning.

The import

use thiserror::Error;

This brings the derive macro into scope. The name Error is the macro, and it is also the name of the standard library trait it implements, std::error::Error. The import is what lets #[derive(Error)] resolve to the macro from the thiserror crate rather than to nothing at all. Without it, the compiler reports that the derive macro cannot be found.

The derive line

#[derive(Error, Debug)]

#[derive(...)] asks the compiler to generate implementations for the listed traits. Error is the thiserror macro, which generates Display and std::error::Error. Debug is the standard derive, which generates the {:?} printing used in logs and tests. Both are required, and the reason is in the standard library: std::error::Error requires Debug and Display as supertraits, which means a type cannot implement Error without implementing both. The macro generates Display, and the Debug derive supplies the other half. Deriving Error without Debug fails to compile, and the failure was verified directly: the compiler reports error E0277, saying the type does not implement Debug, and points at the bound in std::error::Error.

The plain message annotations

    #[error("resource not found")]
    NotFound,
    #[error("something went wrong")]
    InternalError,

#[error("...")] sets the Display output for that variant to the string in quotes. NotFound prints as "resource not found", and InternalError prints as "something went wrong". The annotation sits directly above its variant, so the message and the variant it describes are adjacent in the source, and adding a variant without its annotation is a visible gap rather than a forgotten arm in a distant match.

The interpolating annotation

    #[error("{0}")]
    ValidationError(String),

{0} is a placeholder for the first field of the variant. ValidationError is a tuple variant with one field, a String, so {0} means "print that field here". The Display output for ValidationError("title must not be empty") is therefore the string itself, "title must not be empty", with nothing added. The placeholder syntax mirrors the {} placeholders in format!, and the number counts the fields from zero, so {0} is the first field, {1} would be the second, and so on. Variants with named fields interpolate by name instead, writing the field name inside the braces, but this enum has no named-field variants, so the numbered form is the one it uses.

The Concept Behind Generating Display

The Display implementation is the most repetitive code in an error type, because it is a match that restates what the variants already say. The variant is named NotFound, and the arm writes "resource not found". The variant carries a String, and the arm writes that string. The information is already in the enum definition, and the hand-written implementation repeats it in a second place. Repetition in two places is how the two places drift apart: a variant is renamed, a message is reworded, and one copy is updated while the other is not.

The derive removes the second copy. The message lives on the variant, and the generated code reads it from there. There is no arm to forget, no write! call to mistype, and no match to keep exhaustive by hand, because the macro generates the match from the enum itself. The compiler still checks exhaustiveness, but it checks the generated code, which is always complete, because it was generated from the same enum it matches on.

The Macro Reads the Enum, It Does Not Guess:

The derive macro sees the full enum definition, including every variant and every field, and it generates code from that definition. A variant without an #[error] annotation is an error at compile time, because the macro cannot invent a message for it. The message is always written by you, on the variant, and the macro only turns it into code.

The IntoResponse Change in Detail

The rewrite changes how the message is obtained inside into_response, and the change is worth reading closely, because it shows the two mechanisms working side by side.

impl IntoResponse for AppError {
    fn into_response(self) -> Response {
        let status = match &self {
            AppError::NotFound => StatusCode::NOT_FOUND,
            AppError::ValidationError(_) => StatusCode::UNPROCESSABLE_ENTITY,
            AppError::InternalError => StatusCode::INTERNAL_SERVER_ERROR,
        };
        let message = self.to_string();
        (status, Json(json!({ "error": message }))).into_response()
    }
}

The status match now borrows self with match &self, because the message step still needs the owned value. A match on &self reads the variant without consuming it, so self is still available afterwards for self.to_string(). The ValidationError(_) pattern ignores the inner message in this match, because the status does not depend on the words. Then self.to_string() calls the generated Display implementation and produces the message string, which goes into the JSON body exactly as before.

The order matters: the borrow in the status match ends before to_string() runs, because the match expression finishes and its borrow is released. If the status match were written on self by value, as in the hand-written version, the value would be moved and to_string() would fail to compile with a "use of moved value" error. Matching by reference for the status and consuming by value for the message is the shape that lets both steps share one owned value.

Writing Messages With Prefixes

The {0} placeholder can sit inside a longer message, which lets the annotation add context around the carried value. A validation message that reads better with a prefix is written as a template with the placeholder inside it.

#[derive(Error, Debug)]
pub enum AppError {
    #[error("resource not found")]
    NotFound,
    #[error("validation failed: {0}")]
    ValidationError(String),
    #[error("something went wrong")]
    InternalError,
}

ValidationError("title must not be empty") now prints as "validation failed: title must not be empty", and the JSON body becomes {"error":"validation failed: title must not be empty"}. The prefix is part of the message, and the tests that assert the exact body text would need updating to match it, because the body is a contract. This app keeps the plain "{0}" form, because the handler already writes complete messages, and a prefix would repeat what the message already says. Use a prefix when the carried value on its own is not a complete sentence, and skip it when the handler's message already stands alone.

Adding a Fourth Variant With the Derive

A new failure kind with the derive is three edits in one file: the variant, its annotation, and its status arm. The example below adds a variant for a database that is down, reusing the shape the enum page introduced.

src/errors.rs
use thiserror::Error;

#[derive(Error, Debug)]
pub enum AppError {
    #[error("resource not found")]
    NotFound,
    #[error("{0}")]
    ValidationError(String),
    #[error("something went wrong")]
    InternalError,
    #[error("database is unavailable")]
    DatabaseDown,
}

The annotation gives the variant its message, "database is unavailable", and the status arm gives it its code, 500, because a database that is down is a server-side failure. The compiler enforces both edits: a variant without an annotation fails the derive, and a variant without a status arm fails the match in the response conversion with error E0004. The two checks together mean a new variant cannot be half-added. Either it has its message and its status, or the build fails and says which piece is missing. That is the same guarantee the hand-written version gave, kept intact by the derive.

Reading the Generated Display in a Log

The generated Display implementation is also what a log line prints when the error is formatted with {}. A handler that logs a failure before returning it writes the message, not the variant name, which is what an operator wants to read.

let error = AppError::ValidationError("title must not be empty".to_string());
eprintln!("request failed: {error}");

The terminal prints request failed: title must not be empty, because {error} runs the generated Display and writes its output into the line. The {:?} form would print the variant name with its payload, ValidationError("title must not be empty"), which is useful in a test and noisy in a log. The {} form prints the message alone, which reads like a sentence. The two placeholders give the same error two voices: {:?} for the developer debugging, and {} for the operator reading the log. Both come from the same annotations, and both stay correct when a message is reworded, because there is only one place the message is written.

The Other Attributes in One Sentence Each

The derive supports more attributes than the three annotations this enum uses, and two of them are worth knowing by name, even though this design does not use them. #[from] on a field generates a From implementation that converts the wrapped error into this enum automatically, and the conversion page uses it where error conversion is taught. #[error(transparent)] forwards the Display and the underlying cause straight through to a wrapped error without adding any text, which fits a variant that is a pure pass-through for another error type. Neither belongs in this enum, because its variants are built by hand in handlers, not converted from other errors, and knowing their names is enough for now.

How the Rewrite Flows

The diagram below follows one error from its annotation to the response body, showing the compile-time step and the runtime step separately.

#[error("{0}")] on ValidationError(String)
        |
        v
Compiler runs the derive macro, generates Display
        |
        v
Handler returns Err(ValidationError("title must not be empty"))
        |
        v
into_response reads the status from a match on &self
        |
        v
self.to_string() runs the generated Display, message is the string itself
        |
        v
422 Unprocessable Entity, {"error":"title must not be empty"}

The macro ran at compile time, and everything below it runs at request time. The generated code is invisible in the source and identical in behaviour to the hand-written code it replaced, which is why the responses are unchanged.

Testing the Derived Enum

The tests assert the Display output for each variant, the std::error::Error implementation, and the full round trip through the router. They pin the messages down, so a reworded annotation breaks a test instead of silently changing what clients see.

tests/thiserror_derive_test.rs
use axum::{
    body::Body,
    http::{Request, StatusCode},
    response::IntoResponse,
};
use axum_project::{app, errors::AppError};
use tower::ServiceExt;

#[test]
fn display_messages_match_the_contract() {
    assert_eq!(AppError::NotFound.to_string(), "resource not found");
    assert_eq!(
        AppError::ValidationError("title must not be empty".to_string()).to_string(),
        "title must not be empty"
    );
    assert_eq!(
        AppError::InternalError.to_string(),
        "something went wrong"
    );
}

#[test]
fn derived_error_implements_std_error() {
    let err: &dyn std::error::Error = &AppError::NotFound;
    assert!(err.source().is_none());
}

#[tokio::test]
async fn derived_not_found_returns_404_json() {
    let response = AppError::NotFound.into_response();
    assert_eq!(response.status(), StatusCode::NOT_FOUND);
    let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
        .await
        .unwrap();
    assert_eq!(
        String::from_utf8(bytes.to_vec()).unwrap(),
        r#"{"error":"resource not found"}"#
    );
}

#[tokio::test]
async fn derived_validation_returns_422_with_message() {
    let response =
        AppError::ValidationError("title must not be empty".to_string()).into_response();
    assert_eq!(response.status(), StatusCode::UNPROCESSABLE_ENTITY);
    let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
        .await
        .unwrap();
    assert_eq!(
        String::from_utf8(bytes.to_vec()).unwrap(),
        r#"{"error":"title must not be empty"}"#
    );
}

#[tokio::test]
async fn router_with_derived_error_serves() {
    let response = app()
        .oneshot(
            Request::builder()
                .uri("/books/7")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::NOT_FOUND);
}

The first test calls .to_string() on each variant, which runs the generated Display, and compares the result with the contract messages. The second test treats the error as a dyn std::error::Error trait object and checks that source() returns None, proving the Error implementation exists and that no variant wraps an underlying cause. The remaining tests check the response conversion and the router round trip. All five tests passed against the scratch project with thiserror 2.0.21. Run them with cargo test and expect:

test display_messages_match_the_contract ... ok
test derived_error_implements_std_error ... ok
test derived_not_found_returns_404_json ... ok
test derived_validation_returns_422_with_message ... ok
test router_with_derived_error_serves ... ok

Common Beginner Mistakes

Deriving Error without Debug

// Wrong - std::error::Error requires Debug, and the build fails
use thiserror::Error;

#[derive(Error)]
pub enum AppError {
    #[error("resource not found")]
    NotFound,
    #[error("{0}")]
    ValidationError(String),
    #[error("something went wrong")]
    InternalError,
}

The compiler rejects this with error E0277, saying the type does not implement Debug, and points at the bound in std::error::Error that requires it. The fix is #[derive(Error, Debug)], with both traits in the same derive list. The order inside the list does not matter, but the presence of both does.

Error Without Debug Does Not Compile:

The error message for this mistake is clear once you have seen it, and confusing the first time: it says the type does not implement Debug, not that the derive is wrong. If the compiler complains about a missing Debug on an error enum, check the derive line first.

Forgetting the annotation on a variant

// Wrong - the macro cannot invent a message for this variant
#[derive(Error, Debug)]
pub enum AppError {
    #[error("resource not found")]
    NotFound,
    ValidationError(String),
    #[error("something went wrong")]
    InternalError,
}

Every variant needs its own #[error("...")], because the macro generates the Display output from the annotations, and a variant without one has no output to generate. The compiler reports the missing annotation as an error on the variant. The fix is to add the annotation, with {0} for a variant that carries a message, and a plain string for a unit variant.

Using the wrong placeholder number

// Wrong - the variant has one field, numbered 0, not 1
#[derive(Error, Debug)]
pub enum AppError {
    #[error("resource not found")]
    NotFound,
    #[error("{1}")]
    ValidationError(String),
    #[error("something went wrong")]
    InternalError,
}

Fields are numbered from zero, so a single-field tuple variant has only {0}. {1} refers to a second field that does not exist, and the macro rejects it at compile time. The fix is {0}. When a variant grows a second field, that field becomes {1}, and the annotation must be updated to mention it, or the new field is silently ignored by the message.

Moving self before calling to_string

// Wrong - the status match moves self, so to_string has nothing left
impl IntoResponse for AppError {
    fn into_response(self) -> Response {
        let status = match self {
            AppError::NotFound => StatusCode::NOT_FOUND,
            AppError::ValidationError(_) => StatusCode::UNPROCESSABLE_ENTITY,
            AppError::InternalError => StatusCode::INTERNAL_SERVER_ERROR,
        };
        let message = self.to_string();
        (status, Json(json!({ "error": message }))).into_response()
    }
}

The status match on self by value moves the error into the match, and the to_string() call afterwards fails with a "use of moved value" error. The fix is match &self for the status, which borrows the value and releases it before to_string() runs. The hand-written version avoided this by taking both values out in one match, and the derived version needs the borrow because the two steps are now separate.

Borrow for the Status, Own for the Message:

The status decision only reads the variant, so it borrows. The message decision needs the owned String from the validation variant, so it consumes. Writing the status match on &self is what lets both steps share one value, and it is the shape to copy whenever a method needs to both inspect and consume its argument.

Final Complete Example

Here is everything from this page in one place: the derived enum, the response conversion that uses its Display output, the three handlers, and the server that serves them.

src/errors.rs
use axum::{
    Json,
    http::StatusCode,
    response::{IntoResponse, Response},
};
use serde_json::json;
use thiserror::Error;

#[derive(Error, Debug)]
pub enum AppError {
    #[error("resource not found")]
    NotFound,
    #[error("{0}")]
    ValidationError(String),
    #[error("something went wrong")]
    InternalError,
}

impl IntoResponse for AppError {
    fn into_response(self) -> Response {
        let status = match &self {
            AppError::NotFound => StatusCode::NOT_FOUND,
            AppError::ValidationError(_) => StatusCode::UNPROCESSABLE_ENTITY,
            AppError::InternalError => StatusCode::INTERNAL_SERVER_ERROR,
        };
        let message = self.to_string();
        (status, Json(json!({ "error": message }))).into_response()
    }
}
src/lib.rs
pub mod errors;

use axum::{
    Json,
    extract::Path,
    routing::{get, post},
    Router,
};
use errors::AppError;
use serde::{Deserialize, Serialize};

#[derive(Serialize)]
pub struct Book {
    pub id: u32,
    pub title: String,
}

#[derive(Deserialize)]
pub struct NewBook {
    pub title: String,
}

pub fn app() -> Router {
    Router::new()
        .route("/books/{id}", get(get_book))
        .route("/books", post(create_book))
        .route("/boom", get(boom))
}

async fn get_book(Path(id): Path<u32>) -> Result<Json<Book>, AppError> {
    if id == 1 {
        Ok(Json(Book {
            id: 1,
            title: "The Rust Book".to_string(),
        }))
    } else {
        Err(AppError::NotFound)
    }
}

async fn create_book(Json(input): Json<NewBook>) -> Result<Json<Book>, AppError> {
    if input.title.trim().is_empty() {
        return Err(AppError::ValidationError(
            "title must not be empty".to_string(),
        ));
    }
    Ok(Json(Book {
        id: 2,
        title: input.title,
    }))
}

async fn boom() -> Result<&'static str, AppError> {
    Err(AppError::InternalError)
}
src/main.rs
use axum_project::app;

#[tokio::main]
async fn main() {
    let app = app();
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("Server running at http://127.0.0.1:3000");
    axum::serve(listener, app).await.unwrap();
}

Run the server, check the three failure paths with curl, and the responses match the hand-written version exactly. Run cargo test, and the five derive tests pass.

Summary

The derive completes the error design by removing its last repetitive piece. The enum now carries its messages on its variants, the compiler generates the code that prints them, and the response conversion reads the message from the generated Display while still choosing the status from its own match. The decision framework for the whole cluster is now visible in one file: variants name the failures, annotations write the messages, the match picks the statuses, and the tuple builds the body. Each piece has one job, each job lives in one place, and the compiler guards the seams between them with exhaustiveness checking and trait bounds. The practical rule going forward is simple: when a new failure appears, add a variant with its annotation and its status arm, and the rest of the app, handlers, tests, and clients, picks it up without another edit. That is the payoff of the design, a new error costs three lines, and none of them can be forgotten without the build saying so.