FAQ - Help and questions

How do I customise the 404 and 405 responses in axum?

#axum#routing#errors#jsonpublished 0 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

Router::fallback sets the handler for paths that match no route, and Router::method_not_allowed_fallback sets the handler for a known path called with the wrong method. Both take an ordinary handler, so they can return the same JSON error shape as the rest of the API.

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

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

#1

Answer#

By default an unknown path gives 404 with an empty body and a wrong method gives 405 with an empty body. Two router methods replace them:

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

async fn home() -> &'static str { "home" }

async fn not_found() -> impl IntoResponse {
    (StatusCode::NOT_FOUND, Json(json!({ "error": "no such route" })))
}

async fn wrong_method() -> impl IntoResponse {
    (StatusCode::METHOD_NOT_ALLOWED, Json(json!({ "error": "method not allowed" })))
}

#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/", get(home))
        .fallback(not_found)
        .method_not_allowed_fallback(wrong_method);
    for (m, uri) in [("GET", "/"), ("GET", "/missing"), ("POST", "/")] {
        let res = app.clone().oneshot(Request::builder().method(m).uri(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!("{m} {uri} -> {status} {}", String::from_utf8_lossy(&body));
    }
}
text
GET / -> 200 home
GET /missing -> 404 {"error":"no such route"}
POST / -> 405 {"error":"method not allowed"}

fallback returned the 404 body for /missing, and method_not_allowed_fallback the 405 body for POST /. A fallback is a normal handler, so it can use extractors, for example Uri to put the path in a log line.

Common mistakes#

  • Letting a fallback answer 200. Return the status explicitly, as the tuple here does; otherwise crawlers and clients treat unknown pages as real.

How do I serve a single-page app for unknown paths?#

Use a file service as the fallback; the thread on static files shows fallback_service.

Sources#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet