Skip to content

How to access the request in fallback and error handlers? #3098

Answered by jplatte
FelixZY asked this question in Q&A
Discussion options

You must be logged in to vote

Something like this should work:

use axum::{
    extract::Request,
    middleware::{self, Next},
};
use futures_util::FutureExt as _;

Router::new()
    .method_not_allowed_fallback(|method: http::Method| async move {
        dbg!(method);
        http::StatusCode::METHOD_NOT_ALLOWED.into_response()
    })
    .layer(middleware::from_fn(|request: Request, next: Next| async move {
        let req_id = request.headers().get("x-request-id").cloned();
        match next.run(request).catch_unwind().await {
            Ok(response) => response,
            Err(panic_payload) => {
                dbg!(panic_payload);
                http::StatusCode::INTERNAL_SERVER_ERROR.into_response()

Replies: 2 comments 3 replies

Comment options

You must be logged in to vote
2 replies
@jplatte
Comment options

@FelixZY
Comment options

Comment options

You must be logged in to vote
1 reply
@FelixZY
Comment options

Answer selected by FelixZY
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
3 participants