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:
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));
}
}/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.
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.
Related questions#
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#
- tower-http,
catch_panic: https://docs.rs/tower-http/0.6.11/tower_http/catch_panic/index.html (read 2026-12-05) - The Rust Book, "To panic! or Not to panic!": https://doc.rust-lang.org/book/ch09-03-to-panic-or-not-to-panic.html