Getting current path when handling rejections

Viewed 71

I'd like to know how it would be possible to get HTTP path in Warp's rejection handler? I've got the following rejection method:

pub(crate) async fn handle(err: Rejection) -> Result<impl Reply, Infallible> {
    let response = if err.is_not_found() {
        HttpApiProblem::with_title_and_type_from_status(StatusCode::NOT_FOUND)
    } else if let Some(e) = err.find::<warp::filters::body::BodyDeserializeError>() {
        HttpApiProblem::with_title_and_type_from_status(StatusCode::BAD_REQUEST)
            .set_detail(format!("{}", e))
    } else if let Some(e) = err.find::<Error>() {
        handle_request_error(e)
    } else if let Some(e) = err.find::<warp::reject::MethodNotAllowed>() {
        HttpApiProblem::with_title_and_type_from_status(StatusCode::METHOD_NOT_ALLOWED)
            .set_detail(format!("{}", e))
    } else {
        error!("handle_rejection catch all: {:?}", err);

        HttpApiProblem::with_title_and_type_from_status(StatusCode::INTERNAL_SERVER_ERROR)
    };

    Ok(response.to_hyper_response())
}

For instance, I'd call curl localhost:1234/this-aint-valid-path/123 and would like to have access to /this-aint-valid-path/123 for logging purposes as well as returning this as part of the error response.

1 Answers

It loos like the method err.is_not_found() checks whether the reason matches Reason::NotFound, which is an enumeration variant with no parameters. Rejection structs have no additional metadata beyond their reason, so the code in your question cannot be modified to solve your problem. It is however possible to create a custom reason with whatever metadata you want. The method you're looking for to create that Rejection object is called custom, and the docs for it can be found here.

Related