AppError enum

Learn how one shared AppError enum in src errors.rs holds every error an Axum app can return and why one error type beats many

An AppError enum is a single Rust enum that lists every kind of failure your application can report to a client. It lives in a file called src/errors.rs, it has one variant for each failure, and every handler in the app returns it when something goes wrong. One type, one file, one list of everything that can fail.

Where This Fits

The page about rejection mapping showed how a failed extractor turns into a response before the handler even runs. That covers failures Axum detects for you, like a body that is not valid JSON. AppError covers the other half, the failures only your own code can detect, like a book id that matches nothing in your store or a title the client left empty. The extractor failures belong to Axum, and the application failures belong to this enum.

Think of it like a hospital triage board. Every patient who walks in gets one of a small set of labels, and the label decides what happens next. The board does not treat anyone, it just names the situation clearly so the rest of the system can act on it. AppError is that board for your app.

The Smallest Working Version

Create a project with these files. The enum comes first, then one plain function that uses it.

src/errors.rs
#[derive(Debug)]
pub enum AppError {
    NotFound,
    ValidationError(String),
    InternalError,
}
src/lib.rs
pub mod errors;

use errors::AppError;

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

pub fn find_book(id: u32) -> Result<Book, AppError> {
    match id {
        1 => Ok(Book {
            id: 1,
            title: "The Rust Book".to_string(),
        }),
        _ => Err(AppError::NotFound),
    }
}
src/main.rs
use axum_project::find_book;

fn main() {
    match find_book(1) {
        Ok(book) => println!("Found: {:?}", book),
        Err(error) => println!("Failed: {:?}", error),
    }
    match find_book(99) {
        Ok(book) => println!("Found: {:?}", book),
        Err(error) => println!("Failed: {:?}", error),
    }
}

The Cargo.toml file needs these dependencies for the project the later pages build on:

Cargo.toml
[package]
name = "axum-project"
version = "0.1.0"
edition = "2021"

[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"

[dev-dependencies]
tower = { version = "0.5", features = ["util"] }

Run it with cargo run. The terminal prints two lines, one for the book that exists and one for the id that matches nothing:

Found: Book { id: 1, title: "The Rust Book" }
Failed: NotFound

The first line shows the happy path, a Book value inside Ok. The second line shows the failure path, the NotFound variant inside Err. Nothing about HTTP appears yet, and that is deliberate. The enum is a plain Rust value first, and turning it into an HTTP response is a separate step with its own explanation.

Working Setup:

If cargo run prints Found: Book { id: 1, title: "The Rust Book" } followed by Failed: NotFound, the enum is defined, the function returns it, and the project is ready for the rest of this cluster of pages.

Understanding the Enum Definition Line by Line

The enum definition is short, and every line in it earns its place. A beginner who understands these five lines understands the whole type.

The Debug derive

#[derive(Debug)]

derive is a Rust keyword that asks the compiler to write an implementation for you. Debug is a trait, a named set of behaviour, that lets a value be printed with the {:?} format placeholder. Without this line, println!("{:?}", error) in main would not compile, and neither would the test assertions later on this page. The compiler would report that AppError does not implement Debug. Deriving it costs nothing at runtime, and it makes every error printable in logs and test output.

The pub keyword

pub enum AppError {

pub means public. It says any other file in the project may use this type. The enum lives in src/errors.rs, and handlers live in src/lib.rs, so without pub the handlers could not even name the type. The same applies to the module declaration in lib.rs, which is why that file starts with pub mod errors; instead of mod errors;. A private type in a private module is invisible to the rest of the program, and the compiler will say so plainly if you forget either word.

The three variants

    NotFound,
    ValidationError(String),
    InternalError,

An enum variant is one named option the value can be. NotFound and InternalError are unit variants, which means they carry no extra data. They are just names. ValidationError(String) is a tuple variant, which means it carries one String value inside it. The parentheses hold the data, and the String holds the human readable message explaining what was wrong with the input. When a handler returns AppError::ValidationError("title must not be empty".to_string()), the message travels with the error, and the code that receives the error can read it.

The names use UpperCamelCase, the Rust convention where each word starts with a capital letter and there are no underscores. NotFound, not not_found or NOT_FOUND. The compiler does not enforce this for variants, but the warning it prints for a wrongly cased name is loud enough that you will fix it.

The Concept Behind One Shared Error Type

A Rust function that can fail returns a Result<T, E>. Result is an enum with two variants, Ok holding a success value and Err holding a failure value. The E in Result<T, E> is a single type, one slot, and it can only hold one type. If every handler invented its own error type, the handlers could not share helper functions, and the code that turns errors into responses would need a separate conversion for each type.

One shared enum solves this by making the single slot hold many possibilities. The type is one, and the variants are many. A lookup function returns Result<Book, AppError>, a validation helper returns Result<(), AppError>, and a handler returns Result<Json<Book>, AppError>, all with the same E. The () in Result<(), AppError> means the success case carries no value, which fits a check that either passes silently or fails with an error.

Matching on the enum is exhaustive. When you write a match over AppError, the compiler checks that you handled every variant. If you add a fourth variant later and forget to update a match, the build fails with error E0004, non-exhaustive patterns, naming the variant you missed. That failure is a feature. It turns "I forgot to handle the new error" from a runtime surprise into a compile error you fix before the program ever runs.

One Type Does Not Mean One Message:

Sharing the type does not mean sharing the message. ValidationError carries a different String every time it is built, so each failure can explain itself in its own words while still being the same variant. The type stays small, and the messages stay specific.

Why One Type Instead of Many

A beginner often reaches for a different error type per handler, or a plain String as the error, because it feels quicker. Both choices cost more later, and the cost lands exactly where a beginner least expects it.

A plain String error cannot be matched on. Code that receives Err("not found".to_string()) can only compare text, and text comparisons break the moment someone rewords a message. An enum variant can be matched on by name, so renaming a message never breaks the logic that reacts to the error.

A separate error type per handler cannot be shared. A helper that looks a book up by id would need to return one type for the get handler and another type for the update handler, or the two handlers could not share the helper at all. With one enum, the helper is written once and every handler uses it.

A separate error type per failure also scatters the response logic. The code that turns errors into HTTP responses would need one conversion per type, and a new failure kind would mean a new conversion in a new place. With one enum, there is exactly one conversion, and it is a single match with one arm per variant. That conversion is the subject of its own page, and it only works because the enum is shared.

A Richer Complete Example

The smallest version had one lookup. A realistic app has more than one way to fail, so here the same enum serves a lookup and a validation check side by side.

src/errors.rs
#[derive(Debug)]
pub enum AppError {
    NotFound,
    ValidationError(String),
    InternalError,
}
src/lib.rs
pub mod errors;

use errors::AppError;

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

pub fn find_book(id: u32) -> Result<Book, AppError> {
    match id {
        1 => Ok(Book {
            id: 1,
            title: "The Rust Book".to_string(),
        }),
        _ => Err(AppError::NotFound),
    }
}

pub fn check_title(title: &str) -> Result<(), AppError> {
    if title.trim().is_empty() {
        return Err(AppError::ValidationError(
            "title must not be empty".to_string(),
        ));
    }
    if title.len() > 100 {
        return Err(AppError::ValidationError(
            "title must be at most 100 characters".to_string(),
        ));
    }
    Ok(())
}
src/main.rs
use axum_project::{check_title, find_book};

fn main() {
    println!("{:?}", find_book(1));
    println!("{:?}", find_book(99));
    println!("{:?}", check_title(""));
    println!("{:?}", check_title("Dune"));
}

Running this prints four lines, one per call, and each line shows exactly which variant came back and what data it carried:

Ok(Book { id: 1, title: "The Rust Book" })
Err(NotFound)
Err(ValidationError("title must not be empty"))
Ok(())

check_title returns Result<(), AppError>, so its success case prints as Ok(()), an empty success. The return keyword in front of Err is needed there because the function continues to the length check after the empty check. Without return, the empty-title error would be built and then thrown away, and the function would fall through to Ok(()). In find_book there is no return because the match is the last expression in the function, so its value becomes the function's return value.

Return Early or Fall Through:

A Result value built in the middle of a function does nothing on its own. It only becomes the function's answer when it is returned with return or when it is the last expression. Forgetting return in front of an Err inside an if block is one of the most common beginner mistakes with this pattern, and the compiler will not always catch it, because the code still type checks.

Checking a Variant Without a Full Match

A match is the right tool when every variant needs handling, but a test often only cares about one variant. The matches! macro answers a yes-or-no question about a value without writing a full match.

let error = find_book(99).unwrap_err();
assert!(matches!(error, AppError::NotFound));

find_book(99) returns an Err, and unwrap_err() pulls the error value out of it, panicking if the result was actually an Ok. The matches! macro then checks the value against the pattern AppError::NotFound and returns true or false. The test asserts true. For the tuple variant, the pattern includes an underscore for the payload: matches!(error, AppError::ValidationError(_)) is true for any validation message, and matches!(error, AppError::ValidationError(message) if message == "title must not be empty") adds a guard that checks the message too. The guard is an if condition after the pattern, and the macro only returns true when both the pattern and the guard hold.

Use matches! in tests and in short checks where only one variant matters. Use a full match everywhere the code must react to each variant differently, because the match is what the compiler checks for exhaustiveness. The macro is a shortcut for asking, not a replacement for handling.

Growing the Enum With a New Variant

Sooner or later the app meets a failure the three variants do not describe. The fix is one line in src/errors.rs, a new variant at the end of the list, and the compiler then points at every match that must learn about it.

src/errors.rs
#[derive(Debug)]
pub enum AppError {
    NotFound,
    ValidationError(String),
    InternalError,
    DatabaseDown,
}

Adding DatabaseDown as a unit variant takes one line. The next build fails at each match on AppError that has no arm for it, with error E0004 naming the missing pattern. You add the arm, the build passes, and no failure path is silently ignored. That is the whole workflow, and it is why the enum lives in one file. If the variants were spread across the codebase, a new failure kind would be a search project. Here it is a one-line edit plus the arms the compiler demands.

Do not add a variant for every slightly different message. A variant is a kind of failure, not a sentence. Two different validation messages are still one ValidationError variant with two different strings. Add a variant only when the code that reacts to the error must behave differently, for example when it needs a different status code or a different response shape.

Reading the Error Back With a Match

Code that receives an AppError usually wants to know which variant it got, and match is how it asks. This helper turns any variant into a short label, and it shows the exhaustiveness rule in action.

src/lib.rs
pub mod errors;

use errors::AppError;

pub fn describe(error: &AppError) -> &'static str {
    match error {
        AppError::NotFound => "missing",
        AppError::ValidationError(_) => "bad input",
        AppError::InternalError => "server fault",
    }
}

The function takes &AppError, a reference, because it only reads the error and does not need to own it. The underscore in ValidationError(_) means the inner String is ignored for this purpose, and the pattern still matches. The return type &'static str means a string baked into the program, like "missing", which lives for the whole run of the program and never needs to be freed. If you add a variant to the enum and forget to add an arm here, the compiler refuses to build, which is the exhaustiveness guarantee doing its job.

A Validation Helper That Returns the Shared Error

Validation checks belong in small helper functions that return Result<(), AppError>, not inline in every handler. The helper below checks one rule and either passes silently or fails with a message, and any handler can call it.

src/lib.rs
pub mod errors;

use errors::AppError;

pub fn check_title(title: &str) -> Result<(), AppError> {
    if title.trim().is_empty() {
        return Err(AppError::ValidationError(
            "title must not be empty".to_string(),
        ));
    }
    Ok(())
}

The success value is (), so the caller writes check_title(&input.title)? in a handler and moves on, or calls it in a plain function and matches on the result. The trim() call strips spaces from both ends before the emptiness check, so a title of three spaces counts as empty. A title of spaces is not a title, and the check catches it because it looks at the trimmed text rather than the raw text.

How Errors Flow Through the App

The flow below shows the shape the rest of this cluster builds on. A request reaches a handler, the handler calls plain functions, and those functions return either a value or one of the three variants.

Request arrives
        |
        v
Handler runs
        |
        v
Plain function returns Result
        |
        +-- Ok(value) --> handler builds the success response
        |
        +-- Err(NotFound) --> the missing-resource failure
        |
        +-- Err(ValidationError(message)) --> the bad-input failure
        |
        +-- Err(InternalError) --> the server-side failure

The enum is the narrow point in this diagram. Everything above it is many different functions, and everything below it is one error type. That narrow point is what makes the response conversion simple, because it only ever sees three shapes.

Testing the Enum

The enum is plain Rust, so its tests are plain Rust tests. They live in tests/enum_test.rs and need no server, no network, and no HTTP client.

tests/enum_test.rs
use axum_project::errors::AppError;

#[test]
fn debug_format_names_each_variant() {
    assert_eq!(format!("{:?}", AppError::NotFound), "NotFound");
    assert_eq!(
        format!("{:?}", AppError::ValidationError("bad title".to_string())),
        r#"ValidationError("bad title")"#
    );
    assert_eq!(format!("{:?}", AppError::InternalError), "InternalError");
}

#[test]
fn matching_on_the_enum_is_exhaustive() {
    let label = match AppError::NotFound {
        AppError::NotFound => "missing",
        AppError::ValidationError(_) => "bad input",
        AppError::InternalError => "server fault",
    };
    assert_eq!(label, "missing");
}

The first test checks the Debug output, which is the text you see in logs and in println!("{:?}", error). The r#"..."# syntax is a raw string, which lets the test write quotes inside the string without escaping them. The second test checks that matching works and that each arm produces the label it should. Run them with cargo test, and expect both to pass:

test debug_format_names_each_variant ... ok
test matching_on_the_enum_is_exhaustive ... ok

The tower dev-dependency in Cargo.toml is not used by these two tests. It is there because the handler tests on the following pages use oneshot from tower::ServiceExt to send mock requests through the router, and declaring it now keeps the Cargo.toml identical across the whole cluster.

Tests Import From the Library:

The test file imports axum_project::errors::AppError, which only works because lib.rs declares pub mod errors; and errors.rs declares pub enum AppError. If either pub is missing, the test fails to compile with a privacy error. That failure is useful, because it proves the visibility is doing its job.

Common Beginner Mistakes

Forgetting pub on the enum or the module

// Wrong - handlers cannot name the type
enum AppError {
    NotFound,
    ValidationError(String),
    InternalError,
}
// Wrong - the module is invisible outside lib.rs
mod errors;

Without pub, the type exists but nothing outside its own file can use it. The compiler reports that AppError is private, or that module errors is private. The fix is one word in each place: pub enum AppError and pub mod errors;. When a privacy error appears, check both spots, because the error message points at the use site, not at the missing pub.

A Private Enum Compiles Fine Until It Is Used:

Defining the enum without pub is not an error on its own. The error only appears when another file tries to use it, which can be confusing if the enum file itself looks correct. If the compiler says a type is private, look at the definition, not at the code that uses it.

Defining the enum in main.rs

// Wrong - tests and lib.rs cannot import it from here
// src/main.rs
#[derive(Debug)]
pub enum AppError {
    NotFound,
    ValidationError(String),
    InternalError,
}

main.rs is the binary crate, and lib.rs is the library crate. Code in the library cannot import from the binary, and integration tests import from the library. An enum defined in main.rs is trapped there, so handlers in lib.rs and tests in tests/ cannot see it. The fix is to define it in src/errors.rs and declare the module in lib.rs, exactly as the smallest example does.

Using a String as the error type

// Wrong - messages cannot be matched on, and typos become logic
pub fn find_book(id: u32) -> Result<Book, String> {
    match id {
        1 => Ok(Book { id: 1, title: "The Rust Book".to_string() }),
        _ => Err("not found".to_string()),
    }
}

This compiles and runs, and it is still the wrong shape. The caller can only compare strings, so a reworded message silently changes behaviour, and two different failures with similar wording become indistinguishable. The enum version makes each failure a distinct value the compiler can check, and the message rides along inside the variant that needs it.

Forgetting the Debug derive and then printing the error

// Wrong - {:?} has nothing to use
pub enum AppError {
    NotFound,
    ValidationError(String),
    InternalError,
}
println!("{:?}", error);

The compiler rejects this with an error saying AppError does not implement Debug. The fix is #[derive(Debug)] above the enum. Derive it from the start, even if no code prints the error yet, because logging and tests will want it within the hour.

Final Complete Example

Here is everything from this page in one place: the enum, the lookup, the validation helper, and the demo program that prints each outcome.

src/errors.rs
#[derive(Debug)]
pub enum AppError {
    NotFound,
    ValidationError(String),
    InternalError,
}
src/lib.rs
pub mod errors;

use errors::AppError;

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

pub fn find_book(id: u32) -> Result<Book, AppError> {
    match id {
        1 => Ok(Book {
            id: 1,
            title: "The Rust Book".to_string(),
        }),
        _ => Err(AppError::NotFound),
    }
}

pub fn check_title(title: &str) -> Result<(), AppError> {
    if title.trim().is_empty() {
        return Err(AppError::ValidationError(
            "title must not be empty".to_string(),
        ));
    }
    if title.len() > 100 {
        return Err(AppError::ValidationError(
            "title must be at most 100 characters".to_string(),
        ));
    }
    Ok(())
}

pub fn describe(error: &AppError) -> &'static str {
    match error {
        AppError::NotFound => "missing",
        AppError::ValidationError(_) => "bad input",
        AppError::InternalError => "server fault",
    }
}
src/main.rs
use axum_project::{check_title, describe, find_book};

fn main() {
    println!("{:?}", find_book(1));
    println!("{:?}", find_book(99));
    println!("{:?}", check_title(""));
    println!("{:?}", check_title("Dune"));
    println!("{}", describe(&find_book(99).unwrap_err()));
}

Run it with cargo run, and the last line prints missing, which is the label the describe helper gives to NotFound. Run the tests with cargo test, and the two enum tests pass.

Summary

The decision that shapes everything after it is the choice to give the app exactly one error type. A single enum in one file means every failure has a name, every match on failures is checked by the compiler, and the code that turns failures into responses has exactly one input shape to handle. The practical rule is simple: add a variant when the app must react differently to a failure, and put the differing words in the message carried by the variant you already have. The enum itself never talks HTTP, and that separation is what keeps it easy to test, easy to grow, and easy to reason about. The next step in the design is the conversion that reads each variant and builds the response the client actually receives, and that conversion stays trivial precisely because this enum stays small.