Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 38 ยท Authentication and Errors

Error Handling with IntoResponse

Design an AppError enum for Axum, implement IntoResponse and From conversions so the ? operator works in handlers, return consistent JSON errors and avoid leaking internals, with runnable stand-ins.

Handlers fail in many ways: a row is missing, the JSON is invalid, the database is down, a token has expired. In Axum a handler can return Result<T, E> as long as both T and E implement IntoResponse. That one rule is enough to build a clean error layer: define a single application error type, tell Axum how to turn it into an HTTP response, and let the ? operator do the rest.

This lesson builds that pattern step by step. Axum and its crates are not available on this site's runner, so the real code is read-only and the runnable parts are stand-ins for the same logic (an IntoResponse trait of our own).

The goal

You want handlers to look like this:

Rust
// Real code: read-only.
async fn get_todo(State(db): State<PgPool>, Path(id): Path<i64>) -> Result<Json<Todo>, AppError> {
    let todo = sqlx::query_as::<_, Todo>("SELECT id, title, done FROM todos WHERE id = $1")
        .bind(id)
        .fetch_optional(&db)
        .await?                      // sqlx::Error -> AppError
        .ok_or(AppError::NotFound)?; // explicit 404
    Ok(Json(todo))
}

No match ladders, no manual status codes inside the handler.

Define AppError

An enum with one variant per failure category, not per library error:

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

#[derive(Debug)]
pub enum AppError {
    NotFound,
    BadRequest(String),
    Unauthorized,
    Forbidden,
    Conflict(String),
    Internal(anyhow::Error),
}

impl IntoResponse for AppError {
    fn into_response(self) -> Response {
        let (status, message) = match self {
            AppError::NotFound => (StatusCode::NOT_FOUND, "not found".to_string()),
            AppError::BadRequest(m) => (StatusCode::BAD_REQUEST, m),
            AppError::Unauthorized => (StatusCode::UNAUTHORIZED, "authentication required".into()),
            AppError::Forbidden => (StatusCode::FORBIDDEN, "not allowed".into()),
            AppError::Conflict(m) => (StatusCode::CONFLICT, m),
            AppError::Internal(err) => {
                tracing::error!("internal error: {err:#}"); // full detail to the log only
                (StatusCode::INTERNAL_SERVER_ERROR, "internal server error".into())
            }
        };
        (status, Json(json!({ "error": message }))).into_response()
    }
}

Two principles here. First, internal errors never leak: the client gets a generic message while the real cause (with context) goes to the log. Second, the JSON shape is the same for every error, which makes client code simple.

From conversions and the ? operator

? calls From::from on the error. Implement From for the library errors you want to propagate:

Rust
impl From<sqlx::Error> for AppError {
    fn from(err: sqlx::Error) -> Self {
        match err {
            sqlx::Error::RowNotFound => AppError::NotFound,
            sqlx::Error::Database(db) if db.is_unique_violation() => {
                AppError::Conflict("already exists".into())
            }
            other => AppError::Internal(other.into()),
        }
    }
}

Now .await? on any SQLx call produces the right HTTP status, including turning a unique-constraint violation into 409 Conflict.

The thiserror crate removes the Display boilerplate when you want typed errors in lower layers, and anyhow is handy for the catch-all Internal variant, as above.

Stand-in: the whole chain, runnable

Here is the same design with our own IntoResponse trait and a fake database error:

Rust AppError, From and ? (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The 500 case prints the real cause only to stderr (the "log") while the response body stays generic.

Errors from extractors

Axum's built-in extractors have their own rejections: invalid JSON gives 400 or 422, a wrong Path type gives 400. Their plain-text bodies do not match your JSON shape. Wrap Json in your own extractor (or use axum_extra::extract::WithRejection) so rejections turn into AppError::BadRequest:

Rust
// Real code: read-only.
use axum::extract::rejection::JsonRejection;
use axum_extra::extract::WithRejection;

impl From<JsonRejection> for AppError {
    fn from(r: JsonRejection) -> Self {
        AppError::BadRequest(r.body_text())
    }
}

async fn create(
    WithRejection(Json(input), _): WithRejection<Json<NewTodo>, AppError>,
) -> Result<StatusCode, AppError> {
    // ...
    Ok(StatusCode::CREATED)
}

Validation errors

Validate after deserialization: required fields, ranges, lengths. Return a 422 with field detail so a front end can highlight inputs.

Rust Collecting validation errors (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The validator crate offers #[derive(Validate)] with attributes like #[validate(email)] for the same job. Authentication failures use the same error type: see authentication middleware.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What two traits must T and E satisfy for a handler returning Result<T, E>?

    Axum turns Ok and Err into responses through IntoResponse, so both sides must implement it.
  2. 2. Why does .await? on an SQLx call work in a handler returning Result<_, AppError>?

    The ? operator converts the error with From::from, so a Fromsqlx::Error impl is all it takes.
  3. 3. What should the client see for an unexpected database failure?

    Internal details can reveal schema or infrastructure. Log them, and return a generic message.
  4. 4. Which status fits a unique-constraint violation on signup?

    The request conflicts with existing state (a duplicate), which is what 409 means.

Summary

  • One AppError enum plus impl IntoResponse gives consistent error responses.
  • From impls let ? convert library errors into the right status.
  • Never leak internals: log the cause, return a generic message for 500s.
  • Wrap extractor rejections so they use your JSON error shape.
  • Validation failures return 422 with per-field messages.

Next: Password Hashing and Registration