ปรับแต่งข้อผิดพลาด JSON ด้วย JsonConfig ของ Actix Web
web::Json<T ของ Actix Web แปลง JSON เป็นชนิดข้อมูลและปฏิเสธข้อผิดพลาดก่อนเรียก handler โดย web::JsonConfig กำหนดขนาด body และตัวจัดการข้อผิดพลาดเอง ตัวอย่างนี้ใช้ Actix Web 4.19.0
web::Json ของ Actix Web แปลง JSON เป็นชนิดข้อมูลและปฏิเสธข้อผิดพลาดก่อนเรียก handler โดย web::JsonConfig กำหนดขนาด body และตัวจัดการข้อผิดพลาดเอง ตัวอย่างนี้ใช้ Actix Web 4.19.0
Configure the JSON extractor
การตั้งค่าจำกัด body ของ route ไว้ที่ 4096 ไบต์ ตัวจัดการคงสถานะ HTTP จาก JsonPayloadError และแทนรายละเอียด parser ด้วยรหัส JSON ที่คงที่ ข้อมูลที่ถูกต้องจะถูกส่งกลับโดยไม่บันทึก ค่าเริ่มต้น: JSON หรือ Content-Type ที่ไม่ถูกต้องเป็น 400, body เกินกำหนดเป็น 413; ข้อผิดพลาดขณะอ่านใช้สถานะของข้อผิดพลาดต้นทาง
[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
รัน cargo run ส่ง POST ที่มี {"name":"Notes"} และ Content-Type: application/json ไปยัง http://127.0.0.1:8080/projects คาดหวัง 201 และ {"name":"Notes"} JSON ผิดได้ 400; body เกิน 4096 ไบต์ได้ 413; ทั้งคู่ใช้ {"code":"invalid_request"} ยังไม่ได้คอมไพล์หรือรัน
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)