English 中文(简体)
Actix-web 2.0 JsonConfig差
原标题:Actix-web 2.0 JsonConfig error_handler not working

我有以下代码,所有工作都期望error_handler<>/code>。 我不敢确定什么错误。 如果我提出正确的职位要求,则有200份答复数据。 但是,根据不实要求,Im预计有400人没有获得JSON数据。 它只是说400,但并未退回任何错误的json数据。

Expected Behavior

BAD REQ ->curl -X POST -H “Content-Type: application/json” -d{“bad”:“Someone was here”} localhost:80/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:80/send

status 400

Possible Solution

页: 1 它发挥作用,但后来无法找到<代码>。 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
    }
}

<<>rong>

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
  • Rust Version: rustc 1.45.2 (d3fb005a3 2020-07-31)
  • Actix Web Version: 2.0.0
最佳回答

正如我前面提到的那样,可能的解决办法。

在从作者处获得帮助之后。 他提到,我需要搬出<代码>.app_data,以便删除这一问题,或转而采用新的版本3.0来解决这个问题。

但使用下文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

选择第一上诉国的方法也是错误的。 固定在以内。

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()
}
问题回答

暂无回答




相关问题
Creating an alias for a variable

I have the following code in Rust (which will not compile but illustrates what I am after). For readability purposes, I would like to refer the same string with two different names so that the name of ...

Rust Visual Studio Code code completion not working

I m trying to learn Rust and installed the Rust extension for VSCode. But I m not seeing auto-completions for any syntax. I d like to call .trim() on String but I get no completion for it. I read that ...