Database error variants

Learn how sqlx database errors map onto the shared AppError type, which failures become 404 or 500, and what the server log keeps

A database call can fail in several distinct ways, and this app answers them with one shared error type that has three variants. A missing row becomes NotFound and a 404. A bad request the handler catches itself becomes ValidationError and a 422. Everything else the database reports becomes InternalError and a 500, with the detail written to the server log and kept away from the client. The mapping lives in one From implementation, and every handler in the app uses it through the ? operator.

Where This Fits

Every handler in this cluster returns Result<..., AppError>, and every database call inside them ends with ?. This page is the piece that makes that shape work: the conversion from the error type sqlx produces into the error type the app answers with. It names each database failure, shows which variant it becomes, and explains why the client sees so little while the log keeps so much. The create, read, update, and delete handlers all lean on this mapping, and none of them names a status code for a database failure.

Think of a hospital triage board with three labels. A patient who is not on the register gets the "not found" label. A patient whose form is filled in wrong gets the "bad input" label. Every other problem, a machine that will not start or a record that will not save, gets the "server fault" label, and the details go in the staff log, not on the board. The board is small on purpose, because the staff needs three labels to act on, not thirty. The error mapping works the same way. Three labels for the client, and the full detail in the log.

The Smallest Working Version

Create a project with these files. It has one route, GET /users/{id}, and the whole error mapping, because the mapping is the subject of this page.

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"
sqlx = { version = "0.9", features = ["runtime-tokio", "postgres", "macros", "derive"] }

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

The sqlx line needs four features. runtime-tokio runs sqlx on the Tokio runtime, postgres adds the Postgres driver, macros turns on the query_as! macro used below, and derive turns on the FromRow derive used on the User struct. The tower dev-dependency is only for the test near the end of this page.

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

#[derive(Debug)]
pub enum AppError {
    NotFound,
    ValidationError(String),
    InternalError,
}

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

impl From<sqlx::Error> for AppError {
    fn from(error: sqlx::Error) -> Self {
        match error {
            sqlx::Error::RowNotFound => AppError::NotFound,
            other => {
                eprintln!("database error: {other}");
                AppError::InternalError
            }
        }
    }
}
src/db.rs
use sqlx::{PgPool, postgres::PgPoolOptions};

pub async fn create_pool(database_url: &str) -> Result<PgPool, sqlx::Error> {
    PgPoolOptions::new()
        .max_connections(5)
        .connect(database_url)
        .await
}
src/handlers.rs
use axum::{
    Json,
    extract::{Path, State},
};
use serde::Serialize;
use sqlx::{FromRow, PgPool};

use crate::errors::AppError;

#[derive(Debug, Serialize, FromRow)]
pub struct User {
    pub id: i32,
    pub name: String,
    pub email: String,
}

pub async fn get_user(
    State(pool): State<PgPool>,
    Path(id): Path<i32>,
) -> Result<Json<User>, AppError> {
    let user = sqlx::query_as!(
        User,
        "SELECT id, name, email FROM users WHERE id = $1",
        id
    )
    .fetch_one(&pool)
    .await?;
    Ok(Json(user))
}
src/lib.rs
pub mod db;
pub mod errors;
pub mod handlers;

use axum::{Router, routing::get};
use handlers::get_user;
use sqlx::PgPool;

pub fn app(pool: PgPool) -> Router {
    Router::new()
        .route("/users/{id}", get(get_user))
        .with_state(pool)
}
src/main.rs
use axum_project::{app, db::create_pool};

#[tokio::main]
async fn main() {
    let database_url = std::env::var("DATABASE_URL").expect("DATABASE_URL must be set");
    let pool = create_pool(&database_url)
        .await
        .expect("failed to connect to the database");
    let router = app(pool);
    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, router).await.unwrap();
}

Create the table and one row before running the server:

psql "postgres://axumdocs:axumdocs@127.0.0.1:5432/ch12_crud" -c "CREATE TABLE users (id SERIAL PRIMARY KEY, name TEXT NOT NULL, email TEXT NOT NULL UNIQUE, created_at TIMESTAMPTZ NOT NULL DEFAULT NOW());"
psql "postgres://axumdocs:axumdocs@127.0.0.1:5432/ch12_crud" -c "INSERT INTO users (name, email) VALUES ('Asha', 'asha@example.com');"

Start the server with the connection string in the environment:

DATABASE_URL="postgres://axumdocs:axumdocs@127.0.0.1:5432/ch12_crud" cargo run

The terminal prints Server running at http://127.0.0.1:3000 and waits. In a second terminal, ask for the user with id 1, and then for an id that has no row:

curl http://127.0.0.1:3000/users/1
curl -i http://127.0.0.1:3000/users/99
{"id":1,"name":"Asha","email":"asha@example.com"}
HTTP/1.1 404 Not Found
content-type: application/json
content-length: 30

{"error":"resource not found"}

The first request succeeds, because the row exists. The second request fails inside fetch_one, which produces RowNotFound, and the From implementation turns that error into NotFound, which becomes the 404. The handler body never mentions the 404, and the client never sees the words RowNotFound. The mapping does the whole job between the query and the response.

Working Setup:

If the first curl prints the user and the second prints a 404 with {"error":"resource not found"}, the mapping works end to end. The missing row became a typed error, the typed error became a variant, and the variant became a status and a body.

Understanding the From Implementation Line by Line

The From implementation is nine lines long, and it is the narrow point every database failure in the app passes through. A beginner who understands these nine lines understands the error handling of the whole cluster.

The match on the sqlx error

impl From<sqlx::Error> for AppError {
    fn from(error: sqlx::Error) -> Self {
        match error {
            sqlx::Error::RowNotFound => AppError::NotFound,
            other => {
                eprintln!("database error: {other}");
                AppError::InternalError
            }
        }
    }
}

From is a Rust trait that converts one type into another, and implementing From<sqlx::Error> for AppError teaches the compiler how to turn a sqlx error into an AppError. The ? operator uses that teaching. When a database call fails inside a handler, ? looks for a From implementation that converts the error into the handler's error type, finds this one, and returns early with the converted value. The handler never writes the conversion itself.

The match has two arms. The first arm matches sqlx::Error::RowNotFound, the exact error fetch_one produces when a query returns no rows, and turns it into AppError::NotFound. The second arm matches everything else, binds it to the name other, logs it, and turns it into AppError::InternalError. The order matters: the specific arm comes first, and the catch-all arm comes second, so a missing row never falls through to the generic failure.

The log line

                eprintln!("database error: {other}");

eprintln! prints to the standard error stream, which is the terminal's error channel, separate from the normal output channel. The {other} placeholder prints the error with its Display implementation, which is the human-readable form of the error, including the database message. The line is the only place the database detail survives. The client response carries a fixed message, and the log carries the truth. A person running the server reads the log to learn what actually failed, and the client reads the response to learn that something failed.

The log line runs before the InternalError is returned, so the detail is written even though the client never sees it. If the log line were missing, a 500 would arrive with no record of its cause, and the person running the server would have to guess. Logging first and returning second is the shape to keep.

The sqlx Error Variants

sqlx::Error is an enum, a type with a fixed set of variants, and each variant names one way a database call can fail. The mapping above handles one variant by name and the rest together, but a beginner should know what the rest are, because the log lines they produce are the first clue when something goes wrong.

sqlx error variantWhat it meansWhat this app answers
RowNotFoundA query that must return one row returned none404, AppError::NotFound
DatabasePostgres refused the statement, like a unique violation or a missing table500, AppError::InternalError, detail in the log
IoThe network connection to the database broke500, AppError::InternalError, detail in the log
PoolTimedOutNo connection became free in the pool in time500, AppError::InternalError, detail in the log
PoolClosedThe pool was closed while a query was waiting500, AppError::InternalError, detail in the log
TypeNotFoundThe query returned a type sqlx does not know how to decode500, AppError::InternalError, detail in the log
ColumnNotFoundThe query referred to a column that is not in the result500, AppError::InternalError, detail in the log
ColumnDecodeA column value could not be decoded into the expected Rust type500, AppError::InternalError, detail in the log
ConfigurationThe connection string or pool setting was wrong500, AppError::InternalError, detail in the log

The table is the whole map. One variant is a client answer, and the rest are server faults with the detail in the log. The mapping does not need to name each variant separately, because they all deserve the same client answer: something went wrong on the server, and the detail is in the log. Naming them separately in the code would add arms that all return the same variant, and the catch-all arm already says that.

A beginner should notice which failures are missing from the table. There is no variant for a duplicate email, and no variant for a missing table. Both arrive as Database, the variant that wraps whatever Postgres reported, and the difference between them lives inside that variant, in the error code Postgres attached. The next section opens that variant up.

Inside the Database Variant

sqlx::Error::Database wraps a value that implements the DatabaseError trait, and that value carries three pieces of information: a message, a code, and the name of the constraint that broke, when there is one. The message is the sentence Postgres wrote, like duplicate key value violates unique constraint "users_email_key". The code is a short string Postgres assigns to each kind of failure, and the constraint name identifies the rule that refused the row. The From implementation logs the message through Display, and it does not read the code or the constraint name, because this app has no variant that needs them yet.

The code is worth seeing, because it is how a later mapping tells two database failures apart. A duplicate email carries the code 23505, which Postgres assigns to every unique violation. A missing table carries a different code, and a null in a NOT NULL column carries another. The code is stable across Postgres versions, while the message text can change, so code that reacts to a failure should read the code, not match the message. The snippet below shows how to read it, and it is a diagnostic tool, not a change to the mapping:

src/errors.rs
impl From<sqlx::Error> for AppError {
    fn from(error: sqlx::Error) -> Self {
        match error {
            sqlx::Error::RowNotFound => AppError::NotFound,
            sqlx::Error::Database(database_error) => {
                eprintln!(
                    "database error: {} (code: {:?})",
                    database_error,
                    database_error.code()
                );
                AppError::InternalError
            }
            other => {
                eprintln!("database error: {other}");
                AppError::InternalError
            }
        }
    }
}

The new arm matches Database separately and prints the code next to the message. A duplicate email then logs a line like this:

database error: error returned from database: duplicate key value violates unique constraint "users_email_key" at line 666 (code: Some("23505"))

The code 23505 is the signal a later mapping would use to answer a duplicate email with its own status instead of a 500. The at line 666 before the code is a line number inside the Postgres server source code, the place in the server where the error was raised, and it changes with the Postgres version. This page keeps the answer as a 500, because the app has three variants and no conflict variant, and the code stays in the log as the record of which failure it was. The arm above is shown so the reader knows where the code lives, not so the reader changes the mapping now.

Read the Code, Not the Message:

Postgres error codes are stable identifiers, and error messages are human sentences that can be reworded. Code that decides what to do about a failure should read database_error.code(), which returns values like Some("23505"), and never compare the message text. The message is for the log, and the code is for the logic.

The Concept Behind One Error Type for Every Handler

A handler returns Result<T, AppError>, and the E in that Result is a single type, one slot that can only hold one type. If every database call produced its own error type, the handlers could not share the ? operator, and the code that turns errors into responses would need a 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 returns Result<Json<User>, AppError>, a create returns Result<(StatusCode, Json<User>), AppError>, and a delete returns Result<StatusCode, AppError>, all with the same E.

The From implementation is what makes the slot work for database errors. Without it, a handler that calls fetch_one with ? would fail to compile, because ? would have no rule for turning a sqlx::Error into an AppError. With it, the conversion is automatic, and the handler body holds no error-handling code at all beyond the ? at the end of each fallible line. The conversion lives in one file, and every handler benefits from it.

Matching on the enum is exhaustive, which means the compiler checks that every match over AppError handles every variant. If a fourth variant is added later and a match forgets it, the build fails with an error naming the missing pattern. That failure is a feature. It turns "I forgot to handle the new error" from a runtime surprise into a compile error fixed before the program ever runs.

Why the Client Sees So Little

The 500 body is always {"error":"something went wrong"}, no matter what the database said. The message never names the table, the column, the constraint, or the query. That silence is deliberate, and it has two reasons. The first is security. A database error message can reveal the table name, the column names, and the constraint names, and that information helps an attacker map the database. The client is not trusted with the schema, so the schema stays out of the response. The second is stability. A client that parses the message text to decide what to do breaks the day the message is reworded, while a client that reads the status code keeps working. The status is the contract, and the message is a human sentence for a human reader.

The log is the other half of the bargain. Everything the response hides, the log keeps, and the log is read by the person running the server, who is trusted with the schema. The split is the design: a vague answer for the client, an exact record for the operator, and the two never mixed. A beginner who is tempted to send the database message to the client should remember that the message was written for the log, and the log is where it belongs.

A Richer Complete Example

The smallest version shows the 404 path. A realistic session shows all three client answers from one server, and the log line each one leaves behind. Run the full app, with every route registered, and send three requests that fail in three different ways.

A missing row answers 404, and the log stays silent, because RowNotFound is a normal answer, not a fault worth logging:

curl -i http://127.0.0.1:3000/users/99
HTTP/1.1 404 Not Found
content-type: application/json
content-length: 30

{"error":"resource not found"}

A bad email answers 422, and the log stays silent too, because the handler caught the input itself and never called the database:

curl -i -X POST http://127.0.0.1:3000/users \
  -H "Content-Type: application/json" \
  -d '{"name": "Asha", "email": "not-an-email"}'
HTTP/1.1 422 Unprocessable Entity
content-type: application/json
content-length: 49

{"error":"email must look like name@example.com"}

A duplicate email answers 500, and the log records the constraint that refused it:

curl -i -X POST http://127.0.0.1:3000/users \
  -H "Content-Type: application/json" \
  -d '{"name": "Asha Again", "email": "asha@example.com"}'
HTTP/1.1 500 Internal Server Error
content-type: application/json
content-length: 32

{"error":"something went wrong"}
database error: error returned from database: duplicate key value violates unique constraint "users_email_key" at line 666

Three failures, three statuses, one body shape, and one log line for the one failure that was actually a fault. The 404 and the 422 are answers, not faults, and they leave no log line, because there is nothing for the operator to fix. The 500 is a fault, and it leaves the exact record the operator needs. The at line 666 at the end of the log line is a line number inside the Postgres server source code, not a line in the reader's code, and the number changes with the Postgres version.

When the Database Is Unreachable

The mapping above assumes the pool connects, and the handler fails only when a query fails. When Postgres is not running at all, the failure happens earlier, in main, when create_pool connects. The expect in main turns that failure into a panic, and the program stops before serving any request:

thread 'main' (86682) panicked at src/main.rs:8:10:
failed to connect to the database: PoolTimedOut
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

A panic at startup is the honest answer for a learning project. The server cannot do its job without the database, so starting without one would only produce 500s for every request. The message says PoolTimedOut, not connection refused, because the pool keeps retrying the refused connection until its timeout runs out, and the timeout is the failure that finally surfaces. The number in parentheses after 'main' is the thread id, and it differs on every run. The fix is to start Postgres. The handler mapping never sees this failure, because no handler runs without a pool, and the startup failure belongs to main, not to the error type.

A pool that connects and then loses the database behaves differently. The next query fails, the mapping logs it and answers 500, and the following requests try again, because the pool keeps the connections it has and opens new ones as needed. The app degrades to 500s instead of crashing, and it recovers when the database comes back, because the pool retries the connection on the next request.

A 500 Is Not Always a Bug:

A 500 caused by a missing table or a refused connection is an operations problem, not a code problem, and the fix is in the database, not in the handler. Read the log line before changing code. The log names the cause, and the cause decides whether the fix is a migration, a running server, or a code change.

The Validation Variant Is Not a Database Error

ValidationError never comes from sqlx. It comes from the handler itself, when it checks the input before calling the database. The distinction matters, because the two kinds of failure are caught in different places. A bad email is caught by check_user_input, which returns the variant directly with a message the client can act on. A duplicate email is caught by Postgres, which returns a database error, and the mapping turns it into a 500 with a fixed message. The first failure is the client's fault and the client is told why. The second failure is a conflict the app has not given its own answer yet, and the client is told only that something went wrong.

The boundary between the two is the database call. Everything the handler can check before the call is a validation error with a useful message. Everything the database reports during the call is a server error with the detail in the log. Keeping that boundary clean is what makes the 422 useful: it always means the input was wrong in a way the client can fix, and it never means the database refused a value the handler could not have checked.

What Happens When a Match Arm Is Missing

The match in the From implementation has a catch-all arm, so it compiles no matter how many variants sqlx::Error gains in a future version. A match without a catch-all would fail to compile the day sqlx adds a variant, and the failure would point at this file. The catch-all is the right shape here, because every future database failure deserves the same answer as the current ones: log it and return InternalError. The specific arm exists only for the one failure that deserves a different answer, and the catch-all covers the rest, present and future.

The same reasoning does not apply to the match in IntoResponse, which names all three AppError variants with no catch-all. That match must be exhaustive, because a new AppError variant needs a status and a message of its own, and a catch-all would silently give it the wrong one. The two matches have opposite shapes on purpose: the sqlx match is open, because new database failures are all server faults, and the AppError match is closed, because a new app error needs a deliberate answer.

The Request Flow

The path of a database failure through the app looks like this:

Handler runs a query with ?
        |
        v
sqlx returns Err(sqlx::Error)
        |
        v
From<sqlx::Error> converts it
        |
        +-- RowNotFound --> AppError::NotFound
        |
        +-- anything else --> log the detail, AppError::InternalError
        |
        v
Handler returns Err(AppError) early
        |
        v
IntoResponse turns the variant into a status and a JSON body
        |
        +-- NotFound --> 404 with {"error": "resource not found"}
        |
        +-- ValidationError(message) --> 422 with {"error": message}
        |
        +-- InternalError --> 500 with {"error": "something went wrong"}

The handler body holds none of this. It holds the query and the ?, and the two implementations do the rest. The flow is the same for every handler, because the conversion lives in one place.

Testing the Error Mapping

The test below checks the three client answers without starting a server. It builds the router with a real pool, asks for a missing user, sends a bad create, and sends a duplicate create, and it checks the status of each response.

tests/error_mapping_test.rs
use axum::{
    body::Body,
    http::{Request, StatusCode},
};
use axum_project::{app, db::create_pool};
use tower::ServiceExt;

async fn pool() -> sqlx::PgPool {
    let database_url = std::env::var("DATABASE_URL").expect("DATABASE_URL must be set");
    create_pool(&database_url).await.unwrap()
}

#[tokio::test]
async fn missing_row_maps_to_404() {
    let pool = pool().await;
    let router = app(pool);
    let response = router
        .oneshot(
            Request::builder()
                .uri("/users/999999")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::NOT_FOUND);
    let body = axum::body::to_bytes(response.into_body(), usize::MAX)
        .await
        .unwrap();
    assert_eq!(
        String::from_utf8(body.to_vec()).unwrap(),
        r#"{"error":"resource not found"}"#
    );
}

#[tokio::test]
async fn bad_input_maps_to_422() {
    let pool = pool().await;
    let router = app(pool);
    let response = router
        .oneshot(
            Request::builder()
                .method("POST")
                .uri("/users")
                .header("Content-Type", "application/json")
                .body(Body::from(r#"{"name": "", "email": "asha@example.com"}"#))
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::UNPROCESSABLE_ENTITY);
}

#[tokio::test]
async fn duplicate_email_maps_to_500() {
    let pool = pool().await;
    sqlx::query!("DELETE FROM users").execute(&pool).await.unwrap();
    sqlx::query!("INSERT INTO users (name, email) VALUES ('Asha', 'asha@example.com')")
        .execute(&pool)
        .await
        .unwrap();
    let router = app(pool);
    let response = router
        .oneshot(
            Request::builder()
                .method("POST")
                .uri("/users")
                .header("Content-Type", "application/json")
                .body(Body::from(
                    r#"{"name": "Asha Again", "email": "asha@example.com"}"#,
                ))
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
    let body = axum::body::to_bytes(response.into_body(), usize::MAX)
        .await
        .unwrap();
    assert_eq!(
        String::from_utf8(body.to_vec()).unwrap(),
        r#"{"error":"something went wrong"}"#
    );
}

The first test checks the whole 404 body, because the message is fixed and the test should prove it. The third test documents the current behaviour for a duplicate email: a 500 with the fixed message. That test is written to pin the behaviour, not to praise it. If the app later gives a duplicate email its own status, this test is the one that must change, and its name says exactly what it pins. Run them with the database URL set:

DATABASE_URL="postgres://axumdocs:axumdocs@127.0.0.1:5432/ch12_crud" cargo test -- --test-threads=1
test missing_row_maps_to_404 ... ok
test bad_input_maps_to_422 ... ok
test duplicate_email_maps_to_500 ... ok

The --test-threads=1 flag runs the tests one at a time. The tests share one table, and running them at the same time could make one test delete rows another test is reading.

Never Send the Database Message to the Client:

A tempting shortcut is to put the database error message into the response body, so the client sees the real reason. That leaks the table name, the column names, and the constraint names to anyone who asks, and it turns the message text into a contract the client depends on. Keep the detail in the log, and keep the client body fixed.

Common Beginner Mistakes

Matching on the message text

// Wrong - the message is a human sentence, and it can be reworded
impl From<sqlx::Error> for AppError {
    fn from(error: sqlx::Error) -> Self {
        let message = error.to_string();
        if message.contains("duplicate key") {
            return AppError::InternalError;
        }
        AppError::InternalError
    }
}

Matching on the message text is fragile, because the text is written for humans and can change between Postgres versions, and it is also pointless here, because both branches return the same variant. When a failure needs a different answer, read the error code through the DatabaseError trait, which returns a stable value like Some("23505"), and match on that. The message is for the log, and the code is for the logic.

Logging the error and returning it to the client

// Wrong - the log line is right, and the response is wrong
impl From<sqlx::Error> for AppError {
    fn from(error: sqlx::Error) -> Self {
        match error {
            sqlx::Error::RowNotFound => AppError::NotFound,
            other => AppError::ValidationError(other.to_string()),
        }
    }
}

Putting the database message into ValidationError sends the schema to the client with a 422, which is the wrong status for a server fault and the wrong body for a database error. The client reads a message about a constraint it cannot fix, and the operator loses the log line that names the cause. Log the detail, return the fixed message, and keep the two separate.

Converting every database error to NotFound

// Wrong - a missing table is not a missing row
impl From<sqlx::Error> for AppError {
    fn from(error: sqlx::Error) -> Self {
        match error {
            sqlx::Error::RowNotFound => AppError::NotFound,
            _ => AppError::NotFound,
        }
    }
}

A catch-all that returns NotFound tells the client that a resource is missing when the real problem is a missing table, a lost connection, or a violated constraint. The client then retries a request that can never succeed, or reports a missing user that actually exists. The 404 means one thing, that the named resource does not exist, and only RowNotFound proves that. Everything else is a server fault, and the 500 says so honestly.

Forgetting the From implementation entirely

// Wrong - the ? operator has no rule for turning sqlx::Error into AppError
pub async fn get_user(
    State(pool): State<PgPool>,
    Path(id): Path<i32>,
) -> Result<Json<User>, AppError> {
    let user = sqlx::query_as!(
        User,
        "SELECT id, name, email FROM users WHERE id = $1",
        id
    )
    .fetch_one(&pool)
    .await?;
    Ok(Json(user))
}

Without the From implementation, this handler fails to compile, because ? cannot convert the error. The compiler reports that the ? operator cannot convert sqlx::Error into AppError, and the fix is the implementation in src/errors.rs. The error message points at the ?, not at the missing implementation, which can confuse a beginner. When a ? fails to compile with a conversion error, look for the From implementation first.

Checking That Everything Compiles

Before running cargo run, run cargo check. The query_as! macro needs the database at compile time, so DATABASE_URL must be set for the check as well as for the run:

DATABASE_URL="postgres://axumdocs:axumdocs@127.0.0.1:5432/ch12_crud" cargo check

If the output ends with a Finished line and no errors, there are no type errors, and the SQL passed the compile-time check against the real table. Then run cargo run to start the server.

Final Complete Example

Here is everything from this page put together. The project has one route, one handler, and the shared error and pool files, with the mapping as the centrepiece.

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

#[derive(Debug)]
pub enum AppError {
    NotFound,
    ValidationError(String),
    InternalError,
}

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

impl From<sqlx::Error> for AppError {
    fn from(error: sqlx::Error) -> Self {
        match error {
            sqlx::Error::RowNotFound => AppError::NotFound,
            other => {
                eprintln!("database error: {other}");
                AppError::InternalError
            }
        }
    }
}
src/db.rs
use sqlx::{PgPool, postgres::PgPoolOptions};

pub async fn create_pool(database_url: &str) -> Result<PgPool, sqlx::Error> {
    PgPoolOptions::new()
        .max_connections(5)
        .connect(database_url)
        .await
}
src/handlers.rs
use axum::{
    Json,
    extract::{Path, State},
};
use serde::Serialize;
use sqlx::{FromRow, PgPool};

use crate::errors::AppError;

#[derive(Debug, Serialize, FromRow)]
pub struct User {
    pub id: i32,
    pub name: String,
    pub email: String,
}

pub async fn get_user(
    State(pool): State<PgPool>,
    Path(id): Path<i32>,
) -> Result<Json<User>, AppError> {
    let user = sqlx::query_as!(
        User,
        "SELECT id, name, email FROM users WHERE id = $1",
        id
    )
    .fetch_one(&pool)
    .await?;
    Ok(Json(user))
}
src/lib.rs
pub mod db;
pub mod errors;
pub mod handlers;

use axum::{Router, routing::get};
use handlers::get_user;
use sqlx::PgPool;

pub fn app(pool: PgPool) -> Router {
    Router::new()
        .route("/users/{id}", get(get_user))
        .with_state(pool)
}
src/main.rs
use axum_project::{app, db::create_pool};

#[tokio::main]
async fn main() {
    let database_url = std::env::var("DATABASE_URL").expect("DATABASE_URL must be set");
    let pool = create_pool(&database_url)
        .await
        .expect("failed to connect to the database");
    let router = app(pool);
    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, router).await.unwrap();
}

Run it with:

DATABASE_URL="postgres://axumdocs:axumdocs@127.0.0.1:5432/ch12_crud" cargo run

Then ask for a missing user with:

curl -i http://127.0.0.1:3000/users/99

Summary

The error mapping is a funnel with three exits. Database failures enter through one From implementation, a missing row exits as a 404, a bad input the handler caught exits as a 422, and everything else exits as a 500 with the detail in the log. The handlers never name a status for a database failure, because the mapping names it once, in one file, for every handler at once. The client gets one body shape and three statuses, and the operator gets the exact record of what failed.

The decision to carry forward is about where each failure is judged. A failure the handler can name in words the client can act on is a validation error, decided before the database call. A failure only the database can detect is a server error, decided by the mapping, with the detail in the log. And the one failure that means the resource is not there, the empty result from a query that must return one row, is a 404, decided by the variant, not by the handler. When a new failure arrives, the question is always which of the three exits it belongs to, and the code that reads the Postgres error code is the tool that answers it.