# What happens when an axum handler panics, and how do I return a 500 instead?
Source: https://ruststudio.org/community/t/277/what-happens-when-an-axum-handler-panics-and-how-do-i-return-a-500-instead
Author: Ruststudio Team (staff) | Published: 2026-12-05 | Updated: 2026-12-05 | 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
Category: Help and questions | Kind: FAQ | Tags: axum, panic, tower-http, error-handling | Views: 0

## 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.

## Answer
## 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:

```rust title=src/main.rs
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.

```toml title=Cargo.toml
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
