Rust Playbook

Course › Week 5 · Axum microservice › Day 4 · lesson 32 of 42 · 30 min reading + 45 min practice

Errors as responses

One AppError that turns every failure into the right status code, like Laravel’s exception handler.

IntoResponseAppErrorstatus codes

On this page
  1. 1. An error type that is a response
  2. 2. Handlers with ?
  3. 3. Every answer, for real
  4. Laravel’s exception handler, for comparison
  5. Practice
  6. Remember

The shared state lesson’s handlers ended in map_err(|_| StatusCode::INTERNAL_SERVER_ERROR), which answers correctly and throws the cause away. In Laravel, the exception handler does this job: every exception becomes a response, a ModelNotFoundException a 404, the rest a 500 whose stack trace goes to the log and never to the client.

axum gives you the same in one type. Handlers return Result<…, AppError>; ? turns any failure into an AppError; and AppError knows how to become a response.

1. An error type that is a response

Four variants, one per kind of answer. #[error("…")] (thiserror) writes the message each one shows. Implementing IntoResponse is what makes it usable as the Err side of a handler: axum calls into_response() on whatever comes back.

Internal is the important one. Its detail is logged with error! and replaced by "Server Error", the text Laravel’s production handler shows. A client never sees a table name, a query or a stack trace.

src/main.rs (the error type)
/// Every way a request can fail, and the response each one becomes.
#[derive(Debug, Error)]
enum AppError {
    #[error("{0} not found.")]
    NotFound(&'static str),

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

    #[error("The service is temporarily unavailable. Try again shortly.")]
    Unavailable,

    #[error("internal error: {0}")]
    Internal(String),
}

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

impl IntoResponse for AppError {
    fn into_response(self) -> Response {
        let status = match &self {
            AppError::NotFound(_) => StatusCode::NOT_FOUND,
            AppError::Conflict(_) => StatusCode::CONFLICT,
            AppError::Unavailable => StatusCode::SERVICE_UNAVAILABLE,
            AppError::Internal(_) => StatusCode::INTERNAL_SERVER_ERROR,
        };
        let message = match &self {
            // The detail goes to the log for us, never to the client.
            AppError::Internal(detail) => {
                error!(%detail, "request failed");
                String::from("Server Error")
            }
            other => other.to_string(),
        };
        let mut response = (status, Json(Message { message })).into_response();
        if status == StatusCode::SERVICE_UNAVAILABLE {
            response
                .headers_mut()
                .insert(RETRY_AFTER, HeaderValue::from_static("5"));
        }
        response
    }
}

/// So that ? works on any sqlx call in a handler.
impl From<sqlx::Error> for AppError {
    fn from(error: sqlx::Error) -> AppError {
        match &error {
            sqlx::Error::PoolTimedOut => AppError::Unavailable,
            sqlx::Error::Database(db) if db.code().as_deref() == Some("23505") => {
                AppError::Conflict(String::from("That already exists."))
            }
            _ => AppError::Internal(error.to_string()),
        }
    }
}

The From<sqlx::Error> at the bottom is what makes ? work on database calls (the Week 2 checkpoint showed ? converting through From). It also sorts database errors into the right answer: no free connection within the timeout means the database is down, 503; Postgres error code 23505 is a unique-index violation, 409; anything else is a bug or an outage, 500.

The whole program is in section 3. The error type is shown alone first because it is the part you will copy into every service.

2. Handlers with ?

Every handler now returns Result<…, AppError> and uses ? on each step. fetch_optional(…).await? passes database errors through the From impl; .ok_or(AppError::NotFound("Evaluation"))? turns a missing row into a 404. The handler reads as the happy path, with every failure accounted for.

src/main.rs (the handlers)
#[derive(Clone)]
struct AppState {
    pool: PgPool,
}

#[derive(Serialize, sqlx::FromRow)]
struct Evaluation {
    id: i64,
    school: String,
    status: String,
}

async fn show(
    State(state): State<AppState>,
    Path(id): Path<i64>,
) -> Result<Json<Evaluation>, AppError> {
    let evaluation: Evaluation =
        sqlx::query_as("select id, school, status from evaluations where id = $1")
            .bind(id)
            .fetch_optional(&state.pool)
            .await?
            .ok_or(AppError::NotFound("Evaluation"))?;
    Ok(Json(evaluation))
}

#[derive(Deserialize)]
struct NewBatch {
    reference: String,
    evaluation_ids: Vec<i64>,
}

#[derive(Serialize)]
struct Created {
    id: i64,
}

async fn store(
    State(state): State<AppState>,
    Json(batch): Json<NewBatch>,
) -> Result<(StatusCode, Json<Created>), AppError> {
    let count =
        i32::try_from(batch.evaluation_ids.len()).map_err(|e| AppError::Internal(e.to_string()))?;
    let id: i64 = sqlx::query_scalar(
        "insert into analysis_batches (reference, evaluations) values ($1, $2) returning id",
    )
    .bind(&batch.reference)
    .bind(count)
    .fetch_one(&state.pool)
    .await?;
    Ok((StatusCode::CREATED, Json(Created { id })))
}

/// Written for a migration that adds answers.flagged, deployed before that migration ran.
async fn answers(
    State(state): State<AppState>,
    Path(id): Path<i64>,
) -> Result<Json<Vec<String>>, AppError> {
    let comments: Vec<String> = sqlx::query_scalar(
        "select comment from answers where evaluation_id = $1 and not flagged and comment is not null",
    )
    .bind(id)
    .fetch_all(&state.pool)
    .await?;
    Ok(Json(comments))
}

answers is deliberately broken in the most realistic way: it queries a column, flagged, that a new migration adds, and the code was deployed before php artisan migrate ran.

3. Every answer, for real

The complete program, then a request for each kind of failure:

src/main.rs
use std::env;
use std::time::Duration;

use axum::extract::{Path, State};
use axum::http::header::RETRY_AFTER;
use axum::http::{HeaderValue, StatusCode};
use axum::response::{IntoResponse, Response};
use axum::routing::{get, post};
use axum::{Json, Router};
use serde::{Deserialize, Serialize};
use sqlx::PgPool;
use sqlx::postgres::PgPoolOptions;
use thiserror::Error;
use tokio::net::TcpListener;
use tracing::error;

/// Every way a request can fail, and the response each one becomes.
#[derive(Debug, Error)]
enum AppError {
    #[error("{0} not found.")]
    NotFound(&'static str),

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

    #[error("The service is temporarily unavailable. Try again shortly.")]
    Unavailable,

    #[error("internal error: {0}")]
    Internal(String),
}

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

impl IntoResponse for AppError {
    fn into_response(self) -> Response {
        let status = match &self {
            AppError::NotFound(_) => StatusCode::NOT_FOUND,
            AppError::Conflict(_) => StatusCode::CONFLICT,
            AppError::Unavailable => StatusCode::SERVICE_UNAVAILABLE,
            AppError::Internal(_) => StatusCode::INTERNAL_SERVER_ERROR,
        };
        let message = match &self {
            // The detail goes to the log for us, never to the client.
            AppError::Internal(detail) => {
                error!(%detail, "request failed");
                String::from("Server Error")
            }
            other => other.to_string(),
        };
        let mut response = (status, Json(Message { message })).into_response();
        if status == StatusCode::SERVICE_UNAVAILABLE {
            response
                .headers_mut()
                .insert(RETRY_AFTER, HeaderValue::from_static("5"));
        }
        response
    }
}

/// So that ? works on any sqlx call in a handler.
impl From<sqlx::Error> for AppError {
    fn from(error: sqlx::Error) -> AppError {
        match &error {
            sqlx::Error::PoolTimedOut => AppError::Unavailable,
            sqlx::Error::Database(db) if db.code().as_deref() == Some("23505") => {
                AppError::Conflict(String::from("That already exists."))
            }
            _ => AppError::Internal(error.to_string()),
        }
    }
}

#[derive(Clone)]
struct AppState {
    pool: PgPool,
}

#[derive(Serialize, sqlx::FromRow)]
struct Evaluation {
    id: i64,
    school: String,
    status: String,
}

async fn show(
    State(state): State<AppState>,
    Path(id): Path<i64>,
) -> Result<Json<Evaluation>, AppError> {
    let evaluation: Evaluation =
        sqlx::query_as("select id, school, status from evaluations where id = $1")
            .bind(id)
            .fetch_optional(&state.pool)
            .await?
            .ok_or(AppError::NotFound("Evaluation"))?;
    Ok(Json(evaluation))
}

#[derive(Deserialize)]
struct NewBatch {
    reference: String,
    evaluation_ids: Vec<i64>,
}

#[derive(Serialize)]
struct Created {
    id: i64,
}

async fn store(
    State(state): State<AppState>,
    Json(batch): Json<NewBatch>,
) -> Result<(StatusCode, Json<Created>), AppError> {
    let count =
        i32::try_from(batch.evaluation_ids.len()).map_err(|e| AppError::Internal(e.to_string()))?;
    let id: i64 = sqlx::query_scalar(
        "insert into analysis_batches (reference, evaluations) values ($1, $2) returning id",
    )
    .bind(&batch.reference)
    .bind(count)
    .fetch_one(&state.pool)
    .await?;
    Ok((StatusCode::CREATED, Json(Created { id })))
}

/// Written for a migration that adds answers.flagged, deployed before that migration ran.
async fn answers(
    State(state): State<AppState>,
    Path(id): Path<i64>,
) -> Result<Json<Vec<String>>, AppError> {
    let comments: Vec<String> = sqlx::query_scalar(
        "select comment from answers where evaluation_id = $1 and not flagged and comment is not null",
    )
    .bind(id)
    .fetch_all(&state.pool)
    .await?;
    Ok(Json(comments))
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    tracing_subscriber::fmt()
        .with_writer(std::io::stderr)
        .with_ansi(false)
        .without_time()
        .init();

    // connect_lazy: the server starts even if the database is down, and each request reports it.
    let pool = PgPoolOptions::new()
        .acquire_timeout(Duration::from_secs(1))
        .connect_lazy(&env::var("DATABASE_URL")?)?;
    let app = Router::new()
        .route("/evaluations/{id}", get(show))
        .route("/evaluations/{id}/answers", get(answers))
        .route("/batches", post(store))
        .with_state(AppState { pool });

    let listener = TcpListener::bind("127.0.0.1:3000").await?;
    axum::serve(listener, app)
        .with_graceful_shutdown(async {
            let _ = tokio::signal::ctrl_c().await;
        })
        .await?;
    Ok(())
}
$ curl -si http://127.0.0.1:3000/evaluations/1042
HTTP/1.1 200 OK
content-type: application/json
content-length: 57

{"id":1042,"school":"Alexandria STEM","status":"pending"}
$ curl -si http://127.0.0.1:3000/evaluations/9999
HTTP/1.1 404 Not Found
content-type: application/json
content-length: 35

{"message":"Evaluation not found."}
$ curl -si -H 'content-type: application/json' -d '{"reference": "nightly-2026-12-01", "evaluation_ids": [1042, 1043]}' http://127.0.0.1:3000/batches
HTTP/1.1 201 Created
content-type: application/json
content-length: 8

{"id":1}
$ curl -si -H 'content-type: application/json' -d '{"reference": "nightly-2026-12-01", "evaluation_ids": [1042, 1043]}' http://127.0.0.1:3000/batches
HTTP/1.1 409 Conflict
content-type: application/json
content-length: 34

{"message":"That already exists."}
$ curl -si http://127.0.0.1:3000/evaluations/1042/answers
HTTP/1.1 500 Internal Server Error
content-type: application/json
content-length: 26

{"message":"Server Error"}
the server’s log (stderr), after Ctrl-C
ERROR evaluations: request failed detail=error returned from database: column "flagged" does not exist at line 3722

The second POST with the same reference is a 409, decided by the database’s unique index, not by a check in the code that two requests could both pass at the same time (the race the sqlx lesson’s transactions are about). That is how the service will make Laravel’s retries safe: a retried request with the same reference cannot create a second batch.

The client got {"message":"Server Error"} for the missing column. The server’s log, below the responses, has the real cause in the database’s own words, at ERROR level, where your monitoring will find it. (at line 3722 is a line in Postgres’s source code, which Postgres reports with every error; it is not a line of yours.)

The database is down

The same program, pointed at a database that is not running. connect_lazy lets the server start anyway; each request waits the 1-second acquire timeout, then answers:

$ curl -si http://127.0.0.1:3000/evaluations/1042
HTTP/1.1 503 Service Unavailable
content-type: application/json
retry-after: 5
content-length: 72

{"message":"The service is temporarily unavailable. Try again shortly."}

503 with Retry-After: 5, the answer the reqwest lesson’s retry loop, and Laravel’s Http::retry, know how to handle. A 500 would have said “broken”; a 503 says “not now”.

connect_lazy versus connect: start anyway and report per request, or refuse to start. For a service behind a load balancer, starting and reporting 503 lets the health check take it out of rotation; refusing to start can leave it restarting in a loop. Both are defensible; pick one on purpose.

Laravel’s exception handler, for comparison

bootstrap/app.php (part)
<?php

use Illuminate\Database\QueryException;
use Illuminate\Database\UniqueConstraintViolationException;
use Illuminate\Foundation\Configuration\Exceptions;

return Illuminate\Foundation\Application::configure(basePath: dirname(__DIR__))
    ->withExceptions(function (Exceptions $exceptions) {
        $exceptions->render(fn (UniqueConstraintViolationException $e) => response()->json(['message' => 'That already exists.'], 409));
        $exceptions->render(fn (QueryException $e) => str_contains($e->getMessage(), 'Connection refused')
            ? response()->json(['message' => 'The service is temporarily unavailable.'], 503, ['Retry-After' => 5])
            : null);   // null: fall back to the default 500 handling
    })
    ->create();

The same decisions, registered by exception class. The difference is visibility: in Laravel, any line can throw anything, and the handler catches what arrives. In axum, a handler’s signature says it can fail only with AppError, so every failure has gone through From or an explicit map_err, and the compiler made sure of it.

PracticeThe axum error-handling docs, and a validation variant

Read the error handling page of the axum docs.

Exercise: AppError::Invalid

Fold the JSON lesson’s 422 into AppError: add a variant Invalid(ValidationErrors) that becomes the Laravel-shaped body with message and errors, and an impl From<ValidationErrors> for AppError, so a handler can write batch.validate()?. Then ValidatedJson’s rejection can be an AppError too.

Show the new pieces
src/main.rs (part)
#[derive(Debug, Error)]
enum AppError {
    // … the four variants as before …
    #[error("The given data was invalid.")]
    Invalid(ValidationErrors),
}

impl From<ValidationErrors> for AppError {
    fn from(errors: ValidationErrors) -> AppError {
        AppError::Invalid(errors)
    }
}

// in into_response(), before the general case:
        if let AppError::Invalid(errors) = &self {
            return invalid(errors); // the function from the JSON lesson
        }

Returning early for Invalid keeps its special body out of the shared message logic. Add StatusCode::UNPROCESSABLE_ENTITY to the status match too, so it stays exhaustive.

Remember

  • Handlers return Result<…, AppError>, and AppError decides the status and the body in one place.
  • A 500 logs the detail and shows the client nothing; let the database’s unique index decide conflicts.

Tomorrow: middleware. Request logging, timeouts, CORS, an API key check, and a clean shutdown on deploy.