FAQ - Help and questions

What happens when an axum handler panics, and how do I return a 500 instead?

#axum#panic#tower-http#error-handlingpublished 0 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

A panic is a bug, not an error value. Wrap the router in tower-http CatchPanicLayer and a panicking handler produces a 500 response instead of a dropped request, while the panic message still goes to standard error. Fix the bug; the layer is a safety net, not error handling.

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; tower-http 0.6.11

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

#1

Answer#

Add CatchPanicLayer around the routes. A request whose handler panics gets status 500 with the body Service panicked, and later requests are served normally:

src/main.rsrust
use axum::{body::{to_bytes, Body}, http::Request, routing::get, Router};
use tower::ServiceExt;
use tower_http::catch_panic::CatchPanicLayer;

async fn ok() -> &'static str { "fine" }
async fn boom() -> &'static str { panic!("a bug in a handler") }

#[tokio::main]
async fn main() {
    let app = Router::new().route("/ok", get(ok)).route("/boom", get(boom)).layer(CatchPanicLayer::new());
    for uri in ["/boom", "/ok"] {
        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
/boom -> 500 "Service panicked"
/ok -> 200 "fine"

The panic message itself (a bug in a handler, with file and line) was printed to standard error by Rust's panic hook, so it appears in your log output.

Cargo.tomltoml
tower-http = { version = "0.6.11", features = ["catch-panic"] }

Common mistakes#

  • Using panics for expected failures such as "user not found". Return an error value (see the thread on an error type) so the client gets a precise status.
  • Relying on the layer and never reading the log. Each panic is a bug to fix.
  • Building with panic = "abort" in the release profile: the process then ends on a panic and no layer can catch it.

Does a panic stop the whole server?#

Not with the layer, as the run above shows: /ok answered after /boom. When to panic at all is covered in the thread on panic or Result.

Sources#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet