FAQ - Help and questions

How do I write an error type for axum handlers so that ? works?

#axum#error-handling#thiserror#intoresponsepublished 0 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

Define one enum for your application errors, implement IntoResponse for it to choose a status and a body, and add From conversions (thiserror writes them). Handlers then return Result<T, AppError> and use the question mark. Log the internal detail and send the client a generic message.

Checked with rustc 1.93.0, axum 0.8.9, tokio 1.54.1, tower 0.5.3, Windows 11; handlers called in-process with tower's oneshot; thiserror 2.0.21

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

Answer#

Axum can turn any Result<T, E> into a response when both T and E implement IntoResponse. So give your errors that trait once, and every handler can use ?.

src/main.rsrust
use axum::{
    body::{to_bytes, Body},
    extract::Path,
    http::{Request, StatusCode},
    response::{IntoResponse, Response},
    routing::get,
    Router,
};
use tower::ServiceExt;

#[derive(Debug, thiserror::Error)]
enum AppError {
    #[error("not found")]
    NotFound,
    #[error("bad input: {0}")]
    BadInput(#[from] std::num::ParseIntError),
    #[error("database failure: {0}")]
    Database(String),
}

impl IntoResponse for AppError {
    fn into_response(self) -> Response {
        let (status, message) = match &self {
            AppError::NotFound => (StatusCode::NOT_FOUND, "not found".to_string()),
            AppError::BadInput(e) => (StatusCode::BAD_REQUEST, e.to_string()),
            AppError::Database(_) => {
                eprintln!("log only: {self}"); // the detail goes to the log, not to the client
                (StatusCode::INTERNAL_SERVER_ERROR, "internal error".to_string())
            }
        };
        (status, message).into_response()
    }
}

async fn show(Path(raw): Path<String>) -> Result<String, AppError> {
    let id: u32 = raw.parse()?; // ParseIntError -> AppError::BadInput through #[from]
    match id {
        0 => Err(AppError::Database("connection refused: 10.0.0.5:5432".into())),
        1 => Ok("user 1".into()),
        _ => Err(AppError::NotFound),
    }
}

#[tokio::main]
async fn main() {
    let app = Router::new().route("/users/{id}", get(show));
    for uri in ["/users/1", "/users/9", "/users/x1", "/users/0"] {
        let res = app.clone().oneshot(Request::get(uri).body(Body::empty()).unwrap()).await.unwrap();
        let status = res.status().as_u16();
        let body = to_bytes(res.into_body(), usize::MAX).await.unwrap();
        println!("{uri} -> {status} {}", String::from_utf8_lossy(&body));
    }
}
text
/users/1 -> 200 user 1
/users/9 -> 404 not found
/users/x1 -> 400 invalid digit found in string
log only: database failure: connection refused: 10.0.0.5:5432
/users/0 -> 500 internal error
  • #[from] on ParseIntError lets raw.parse()? convert the error into AppError::BadInput without a map_err.
  • The database error carries the server address (10.0.0.5:5432) in its text. The client got only internal error; the detail went to the log line printed by eprintln! (use tracing::error! in a real server).
  • Each variant picks its own status: 404, 400, 500.
Cargo.tomltoml
thiserror = "2.0.21"

Common mistakes#

  • Sending error.to_string() of an internal error to the client. It can reveal hosts, file paths and SQL.
  • One String as the error type for everything: the status then cannot depend on the kind of error.

Should the body be text or JSON?#

For an API, JSON in one fixed shape is easier for clients. The (status, Json(...)) tuple works the same way as the (status, String) used here.

What about panics?#

A panic is not an error value. See the thread on catching panics in a handler.

Sources#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet