Learn Axum · 7/13

Elegant Error Handling

6 min read

Course: Axum
Topic ID: 7


👋 Welcome Back, Camper!

If you’ve made it this far, you’ve probably built a few routes, returned some basic strings, and maybe even panicked your server once or twice (don’t worry, we all do it).

Today, we are tackling one of the most critical aspects of backend engineering: Error Handling.

In many frameworks, error handling is an afterthought—a bunch of try-catch blocks scattered like confetti. In Rust and Axum, it’s a first-class citizen. It’s the difference between a server that crashes silently and one that politely tells the frontend, "Hey, you forgot the password, try again."

We are going to move from "it compiles" to "it’s production-ready."


1. The Problem: Dealing with Result in Route Handlers

Before we fix it, let's break it.

In Rust, the standard way to handle operations that might fail is the Result<T, E> type. In an Axum handler, you might be tempted to do something like this:

rust
async fn create_user(Json(payload): Json<CreateUser>) -> Result<Json<User>, String> {
    // 1. Maybe this fails because the username is taken
    let user = database::insert_user(payload).await.map_err(|e| e.to_string())?;

    // 2. Maybe this fails because the email server is down
    email_service::send_welcome_email(&user).await.map_err(|e| e.to_string())?;

    Ok(Json(user))
}

🛑 Why is this bad?

  1. Stringly Typed Errors: Converting everything to String (map_err(|e| e.to_string())) loses context. You don't know if it was a database error (500 Internal Server Error) or a validation error (400 Bad Request). Everything becomes a generic 500 or 200 with a text body.
  2. Boilerplate City: Writing .map_err(...) on every single line is tedious.
  3. Inconsistent APIs: Your frontend developer will hate you. Sometimes they get a JSON object, sometimes they get a raw string saying "DB Error."

The "Compile" Problem

Axum handlers expect the return type to implement IntoResponse.
If your function returns Result<T, E>, both T (success) and E (error) must implement IntoResponse.

Standard Rust errors (like std::io::Error or sqlx::Error) do not implement IntoResponse by default. Why? Because Axum doesn't know if a database failure should be a 404, a 400, or a 500. You have to tell it.


2. Custom App Errors: Creating a Unified Error Enum

To solve the "Spaghetti Error" problem, we use a central Enum. This is the industry-standard way to manage errors in Rust web services.

Think of this Enum as a funnel. No matter what goes wrong in your app (DB breaks, S3 is down, bad input), it gets converted into one of these variants.

We will use the thiserror crate. It saves us from writing a mountain of boilerplate code for Display and From implementations.

📦 Setup

Add this to your Cargo.toml:

toml
[dependencies]
thiserror = "1.0"
axum = "0.7"
serde = { version = "1.0", features = ["derive"] }

🛠️ The Implementation

Create a file named errors.rs:

rust
use thiserror::Error;

#[derive(Error, Debug)]
pub enum AppError {
    // 1. The user messed up (400)
    #[error("Invalid request: {0}")]
    ValidationError(String),

    // 2. The user isn't allowed (401/403)
    #[error("Authentication failed")]
    AuthError,

    // 3. The resource isn't there (404)
    #[error("User not found with ID: {0}")]
    UserNotFound(u64),

    // 4. Something went wrong inside (500)
    // We wrap the actual error (like sqlx::Error) to keep the logs clean
    #[error("Database error")]
    DatabaseError(#[from] sqlx::Error),
    
    // Catch-all for other unexpected stuff
    #[error("Internal server error")]
    Anyhow(#[from] anyhow::Error),
}

🧐 What just happened?

  • #[derive(Error)]: thiserror generates the code to make this a real Rust std::error::Error.
  • #[from]: This is the magic. It automatically generates impl From<sqlx::Error> for AppError.
    • This means in your handler, you can simply use the ? operator on a database call. If it fails, Rust automatically converts the DB error into AppError::DatabaseError.

3. Implementing IntoResponse for Custom Errors

Now we have a fancy Enum, but Axum still doesn't know how to send it over HTTP. We need to implement the IntoResponse trait.

This acts as a translation layer. It maps your Rust Logic (Enum Variant) to HTTP Logic (Status Code + Body).

In errors.rs:

rust
use axum::{
    http::StatusCode,
    response::{IntoResponse, Response},
    Json,
};
use serde_json::json;

impl IntoResponse for AppError {
    fn into_response(self) -> Response {
        // 1. Determine the status code based on the error variant
        let (status, error_message) = match self {
            AppError::ValidationError(msg) => (StatusCode::BAD_REQUEST, msg),
            AppError::AuthError => (StatusCode::UNAUTHORIZED, "Invalid credentials".to_string()),
            AppError::UserNotFound(id) => (StatusCode::NOT_FOUND, format!("User {} not found", id)),
            AppError::DatabaseError(_) | AppError::Anyhow(_) => {
                // ⚠️ SECURITY NOTE: Don't leak internal DB errors to the public!
                // Log the actual error internally, but return a generic message to the user.
                tracing::error!("Internal Error: {:?}", self); 
                (StatusCode::INTERNAL_SERVER_ERROR, "Something went wrong".to_string())
            },
        };

        // 2. Create a JSON body
        let body = Json(json!({
            "error": error_message,
        }));

        // 3. Combine them into a response
        (status, body).into_response()
    }
}

💡 Interesting Fact

In large distributed systems, leaking raw error messages (like SQL syntax error near 'DROP TABLE') is a massive security vulnerability. It gives hackers a map of your database structure. By mapping DatabaseError to a generic "Something went wrong," you are actually hardening your security!


4. Centralized Error Responses: Returning Consistent JSON

Now, let's look at how elegant our handlers become.

The Improved Handler

rust
// Use our custom Result type alias for cleaner signatures
type AppResult<T> = Result<T, AppError>;

async fn create_user(Json(payload): Json<CreateUser>) -> AppResult<Json<User>> {
    
    // Validation Logic
    if payload.username.is_empty() {
        // We return our custom error directly
        return Err(AppError::ValidationError("Username cannot be empty".into()));
    }

    // Database Logic
    // Look at that beautiful '?' operator! 
    // If insert_user fails with sqlx::Error, it automatically becomes AppError::DatabaseError
    let user = database::insert_user(payload).await?; 

    Ok(Json(user))
}

Why is this "Elegant"?

  1. No map_err noise: The ? works natively because we derived From.
  2. Type Safety: We are guaranteed to return valid JSON or a valid Error Response.
  3. Centralized Control: If you decide tomorrow that all AuthErrors should return a 403 instead of 401, you change it in one place (errors.rs), not in 50 different handlers.

Ensuring Consistent JSON Format

Frontend developers rely on predictable error structures. You don't want to return {"msg": "error"} in one endpoint and {"error": "msg"} in another.

We can formalize the structure inside our IntoResponse implementation:

rust
use serde::Serialize;

#[derive(Serialize)]
struct ErrorResponse {
    status: String,
    message: String,
}

impl IntoResponse for AppError {
    fn into_response(self) -> Response {
        let (status, message) = match self {
            AppError::ValidationError(msg) => (StatusCode::BAD_REQUEST, msg),
            // ... (other matches)
            _ => (StatusCode::INTERNAL_SERVER_ERROR, "Internal server error".to_string()),
        };

        // Construct the consistent JSON body
        let body = Json(ErrorResponse {
            status: "error".to_string(),
            message,
        });

        (status, body).into_response()
    }
}

Now, every error your API produces looks exactly like this:

json
{
  "status": "error",
  "message": "User 123 not found"
}

🧪 Quick Recap

  1. Don't return Strings or raw Results in handlers.
  2. Do create an AppError enum using thiserror.
  3. Do implement IntoResponse to map those enum variants to HTTP Status Codes.
  4. Do use the ? operator in handlers to automatically propagate errors up to Axum.

This setup separates your Business Logic (the handler) from your Transport Logic (HTTP codes/JSON). That is the hallmark of clean architecture.


📚 References & Further Reading

Challenge

Challenge: Concurrent Data Fetching with async/await

Your task is to implement a series of functions that simulate fetching data from different API endpoints and then aggregate the results. This is a common pattern for loading data in a web application.

  1. Implement fetchUserData(userId):

    • This function must return a Promise.
    • It should simulate a network delay of 1000 milliseconds using setTimeout.
    • If the provided userId is a number, the promise should resolve with an object: { id: userId, name: 'John Doe', email: '[email protected]' }.
    • If the userId is not a number, the promise should reject with an error message: 'Invalid user ID'.
  2. Implement fetchUserPosts(userId):

    • This function must also return a Promise.
    • It should simulate a network delay of 1500 milliseconds using setTimeout.
    • If the provided userId is a number, the promise should resolve with an array of post objects: [{ postId: 1, title: 'First Post' }, { postId: 2, title: 'Second Post' }].
    • If the userId is not a number, the promise should reject with an error message: 'Invalid user ID'.
  3. Implement getUserProfile(userId):

    • This function must be an async function.
    • Inside this function, you must call fetchUserData and fetchUserPosts concurrently for the given userId. Use Promise.all to achieve this.
    • Use a try...catch block to handle potential promise rejections.
    • If both promises resolve successfully, the function should return a single aggregated object with the following structure: { user: <userData>, posts: <userPosts> }.
    • If either promise rejects, the catch block should catch the error and the function should return the error's message string.

Expected result

Your final code should contain complete implementations for all three functions (fetchUserData, fetchUserPosts, and getUserProfile) according to the rules specified in the instructions.

  • fetchUserData must return a new Promise that uses setTimeout to delay its resolution or rejection by 1000ms.
  • fetchUserPosts must return a new Promise that uses setTimeout to delay its resolution or rejection by 1500ms.
  • getUserProfile must be an async function that correctly uses await with Promise.all to execute the two fetch functions in parallel.
  • getUserProfile must wrap its asynchronous logic in a try...catch block to handle errors gracefully.
  • When successful, getUserProfile(1) should eventually return an object like: { user: { id: 1, name: 'John Doe', email: '[email protected]' }, posts: [{ postId: 1, title: 'First Post' }, { postId: 2, title: 'Second Post' }] }.
  • When it fails (e.g., getUserProfile('a')), it should return the string 'Invalid user ID'.
javascript

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.