简体   繁体   English

Actix-web 2.0 JsonConfig error_handler 不工作

[英]Actix-web 2.0 JsonConfig error_handler not working

I have this below code, everything works expect the error_handler .我有下面的代码,一切正常都需要error_handler I'm not sure whats wrong.我不确定有什么问题。 If I make post request with correct format I get 200 with response data.如果我以正确的格式发出发布请求,我会得到 200 响应数据。 But on bad request I'm expecting 400 with JSON data which is not receiving.但是在糟糕的请求下,我期望 400 带有未接收的 JSON 数据。 It just says 400, but doesn't return any error json data.它只是说 400,但不返回任何错误 json 数据。

Expected Behavior预期行为

BAD REQ -> curl -X POST -H "Content-Type: application/json" -d '{"bad": "Someone was here"}' localhost:8080/send BAD REQ -> curl -X POST -H "Content-Type: application/json" -d '{"bad": "Someone was here"}' localhost:8080/send

status 400
{
    error: String,
    server_id: usize,
    request_count: usize,
}

Current Behavior当前行为

BAD REQ -> curl -X POST -H "Content-Type: application/json" -d '{"bad": "Someone was here"}' localhost:8080/send BAD REQ -> curl -X POST -H "Content-Type: application/json" -d '{"bad": "Someone was here"}' localhost:8080/send

status 400

Possible Solution可能的解决方案

I replaced .data with .app_data it works, but then it not able to find AppState我用.app_data替换了.data它可以工作,但是它无法找到AppState

Code代码

pub struct MessageApp {
    pub port: u16,
}

impl MessageApp {
    pub fn new(port: u16) -> Self {
        Self{port}
    }

    pub async fn run(&self) -> std::io::Result<()> {
        let messages = Arc::new(Mutex::new(vec![]));
        println!("Starting http server: 127.0.0.1:{}", self.port);

        HttpServer::new(move || {
            App::new()
                .data(AppState {
                    server_id: SERVER_COUNTER.fetch_add(1, Ordering::SeqCst),
                    request_count: Cell::new(0),
                    messages: messages.clone(),
                })
                .wrap(middleware::Logger::new(LOG_FORMAT))
                .service(index)
                .service(
                    web::resource("/send")
                    .data(
                        web::JsonConfig::default()
                            .limit(4096)
                            .error_handler(post_error)
                    )
                    .route(web::post().to(post))
                )
                .service(clear)
        })
        .bind(("127.0.0.1", self.port))?
        .workers(8)
        .run()
        .await
    }
}

error handler错误处理程序

fn post_error(err: JsonPayloadError, req: &HttpRequest) -> Error {
    let extns = req.extensions();
    let state = extns.get::<web::Data<AppState>>().unwrap();
    let request_count = state.request_count.get() + 1;
    state.request_count.set(request_count);

  let post_error = PostError {
      server_id: state.server_id,
      request_count,
      error: format!("{}", err),
  };

  InternalError::from_response(err, HttpResponse::BadRequest().json(post_error)).into()
}

Environment环境

  • Pop OS 20.04 LTS流行操作系统 20.04 LTS
  • Rust Version: rustc 1.45.2 (d3fb005a3 2020-07-31) Rust 版本:rustc 1.45.2 (d3fb005a3 2020-07-31)
  • Actix Web Version: 2.0.0 Actix Web 版本:2.0.0

As I mentioned before in possible solutions.正如我之前在可能的解决方案中提到的。

After taking help from author on github.在 github 上获得作者的帮助后。 He mentioned I need to move out .app_data to get rid of this issue or move on to new version 3.0 which resolves this issue.他提到我需要移出.app_data以摆脱此问题或移至解决此问题的新版本 3.0。

But using version 2.0.0 below is the solution:但是使用下面的 2.0.0 版本是解决方案:

HttpServer::new(move || {
            App::new()
                .data(AppState {
                    server_id: SERVER_COUNTER.fetch_add(1, Ordering::SeqCst),
                    request_count: Cell::new(0),
                    messages: messages.clone(),
                })
                .wrap(middleware::Logger::new(LOG_FORMAT))
                .service(index)
                .service(
                    web::resource("/send")
                    .app_data(
                        web::JsonConfig::default().limit(4096).error_handler(post_error)
                    )
                    .route(web::post().to(post))
                )
                .service(clear)
        })
        .bind(("127.0.0.1", self.port))?
        .workers(8)
        .run()
        .await

As well the method for extracting AppState I was doing wrong.以及提取 AppState 的方法我做错了。 which fixed below inside post_error function.它在post_error function 内部修复。

fn post_error(err: JsonPayloadError, req: &HttpRequest) -> Error {
    // let extns = req.extensions();
    // let state = extns.get::<web::Data<AppState>>().unwrap();
    let state = req.app_data::<web::Data<AppState>>().unwrap();
    let request_count = state.request_count.get() + 1;
    state.request_count.set(request_count);

    let post_error = PostError {
        server_id: state.server_id,
        request_count,
        error: format!("{}", err),
    };

    InternalError::from_response(err, HttpResponse::BadRequest().json(post_error)).into()
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从带有客户端的actix-web处理程序向调用者返回错误? - How to return an error to caller from an actix-web handler with client? Rust actix-web:特征 `Handler&lt;_, _&gt;` 未实现 - Rust actix-web: the trait `Handler<_, _>` is not implemented 使用 actix-web 2.0 提供 static 文件 - Serving static files with actix-web 2.0 Rust actix-web 在 docker “拒绝连接”错误中不起作用 - Rust actix-web not working in docker "refused to connect" error 尝试从actix-web路由处理程序功能内发出请求时出现错误“ BlockingClientInFutureContext” - Error “BlockingClientInFutureContext” when trying to make a request from within an actix-web route handler function 如何在 Actix-web 中的 WebSocket 处理程序中正确调用异步函数 - How to correctly call async functions in a WebSocket handler in Actix-web actix-web app_data 在请求处理程序中始终为 None - actix-web app_data is always None in request handler 总是返回 Ok HttpResponse 然后在 actix-web 处理程序中工作 - Always return Ok HttpResponse then do work in actix-web handler 为什么这个错误试图有条件地包装我的 actix-web 应用程序? - Why this error trying to conditionally wrap my actix-web app? 多个actix-web客户端请求-预期的结构actix_web :: Error找到() - Multiple actix-web client requests - expected struct actix_web::Error found ()
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM