تخصيص أخطاء JSON باستخدام JsonConfig في Actix Web
يحوّل web::Json<T في Actix Web JSON إلى نوع بيانات، ويرفض الإخفاق قبل تشغيل المعالج. يضبط web::JsonConfig حدّ الحمولة ومعالج الخطأ. المثال لـ Actix Web 4.19.0.
يحوّل web::Json في Actix Web JSON إلى نوع بيانات، ويرفض الإخفاق قبل تشغيل المعالج. يضبط web::JsonConfig حدّ الحمولة ومعالج الخطأ. المثال لـ Actix Web 4.19.0.
Configure the JSON extractor
يحد الإعداد جسم هذا المسار بـ4096 بايت. يحافظ المعالج على حالة HTTP الخاصة بـJsonPayloadError ويستبدل تفاصيل المحلل برمز JSON ثابت. المعالج يعيد الإدخال الصحيح دون حفظه. افتراضيًا: JSON غير صالح أو Content-Type غير مقبول يعيد 400، والجسم المتجاوز للحد يعيد 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"} إلى http://127.0.0.1:8080/projects مع Content-Type: application/json. المتوقع 201 و{"name":"Notes"}. JSON غير صالح يعيد 400 والجسم الذي يتجاوز 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)