Tùy chỉnh lỗi JSON bằng JsonConfig của Actix Web
web::Json<T của Actix Web giải tuần tự hóa JSON và từ chối lỗi trước khi chạy handler. web::JsonConfig đặt giới hạn phần thân và bộ xử lý lỗi tùy chỉnh. Ví dụ dùng Actix Web 4.19.0.
web::Json của Actix Web giải tuần tự hóa JSON và từ chối lỗi trước khi chạy handler. web::JsonConfig đặt giới hạn phần thân và bộ xử lý lỗi tùy chỉnh. Ví dụ dùng Actix Web 4.19.0.
Configure the JSON extractor
Cấu hình giới hạn body của route ở 4096 byte. Bộ xử lý giữ trạng thái HTTP của JsonPayloadError và thay chi tiết parser bằng mã JSON ổn định. Dữ liệu hợp lệ được trả về nhưng không lưu. Mặc định JSON hoặc Content-Type không hợp lệ trả 400, quá giới hạn trả 413; lỗi đọc theo trạng thái lỗi nền.
[dependencies]
actix-web = "4.19.0"
serde = { version = "1", features = ["derive"] }Dependencies
use actix_web::{
error,
web::{self, Json},
App, HttpResponse, HttpServer, Responder, ResponseError,
};
use serde::{Deserialize, Serialize};
#[derive(Deserialize, Serialize)]
struct CreateProject {
name: String,
}
#[derive(Serialize)]
struct ApiError {
code: &'static str,
}
async fn create_project(input: Json<CreateProject>) -> impl Responder {
HttpResponse::Created().json(input.0)
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| {
let json_config = web::JsonConfig::default()
.limit(4096)
.error_handler(|err, _req| {
let status = err.status_code();
let response = HttpResponse::build(status).json(ApiError {
code: "invalid_request",
});
error::InternalError::from_response(err, response).into()
});
App::new()
.app_data(json_config)
.route("/projects", web::post().to(create_project))
})
.bind(("127.0.0.1", 8080))?
.run()
.await
}src/main.rs
undefined
Verify locally
Chạy cargo run. Gửi POST với {"name":"Notes"} và Content-Type: application/json tới http://127.0.0.1:8080/projects. Mong đợi 201 và {"name":"Notes"}. JSON lỗi trả 400; body trên 4096 byte trả 413; cả hai dùng {"code":"invalid_request"}. Chưa biên dịch hay chạy.
Official sources
[Actix Web 4.19.0 source 1](https://actix.rs/docs/extractors)
[Actix Web 4.19.0 source 2](https://docs.rs/actix-web/4.19.0/actix_web/web/struct.JsonConfig.html)
[Actix Web 4.19.0 source 3](https://docs.rs/actix-web/4.19.0/actix_web/error/enum.JsonPayloadError.html)
[Actix Web 4.19.0 source 4](https://actix.rs/docs/errors)