首页 > 解决方案 > 处理拒绝时获取当前路径

问题描述

我想知道如何在 Warp 的拒绝处理程序中获取 HTTP 路径?我有以下拒绝方法:

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())
}

例如,我会打电话curl localhost:1234/this-aint-valid-path/123并希望能够访问以/this-aint-valid-path/123进行日志记录,并将其作为错误响应的一部分返回。

标签: rustrust-warp

解决方案


它看起来像方法err.is_not_found()检查原因是否匹配Reason::NotFound,这是一个没有参数的枚举变体。Rejection结构没有超出其原因的其他元数据,因此无法修改您问题中的代码来解决您的问题。但是,可以使用您想要的任何元数据创建自定义原因。您正在寻找的用于创建该Rejection对象的方法称为custom,并且可以在此处找到它的文档。


推荐阅读