Axum catch-all error page
⚓ Rust 📅 2026-02-13 👤 surdeus 👁️ 1I'm using Tera templates with axum to generate pages for a user-facing web app. The Tera instance is passed around in Arc<State> for use by handlers.
I've implemented IntoResponse for my custom error type. However, I'd like to generate a nicer error page for users. I could instantiate a new Tera instance in the IntoResponse impl, but that seems wasteful.
The solution I landed on was a middleware that checks for server error in the response, and renders a Tera template there, as middleware has access to state. But, this seems sub-optimal. Is there a better way?
// to be used with middleware::from_fn_with_state
pub async fn error_page(
State(tera): State<tera::Tera>,
request: Request,
next: Next,
) -> Result<Response, WebappError> {
let response = next.run(request).await;
let status_code = response.status();
if status_code.is_server_error() {
let mut context = tera::Context::new();
context.insert("content", "Something broke");
let rendered = tera.render("error.html", &context)?;
Ok(Html(rendered).into_response())
} else {
Ok(response)
}
}
1 post - 1 participant
🏷️ Rust_feed