خطاهای JSON را با JsonConfig در Actix Web سفارشی کنید
web::Json<T در Actix Web، JSON را به نوع داده تبدیل میکند و پیش از اجرای handler خطا را رد میکند. web::JsonConfig محدودیت بدنه و handler خطای سفارشی را تنظیم میکند. نمونه برای Actix Web 4.19.0 است.
web::Json در Actix Web، JSON را به نوع داده تبدیل میکند و پیش از اجرای handler خطا را رد میکند. web::JsonConfig محدودیت بدنه و handler خطای سفارشی را تنظیم میکند. نمونه برای Actix Web 4.19.0 است.
Configure the JSON extractor
این پیکربندی بدنهٔ این مسیر را به 4096 بایت محدود میکند. handler وضعیت HTTP مربوط به JsonPayloadError را حفظ میکند و جزئیات parser را با کد 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"} و Content-Type: application/json را به http://127.0.0.1:8080/projects بفرستید؛ انتظار 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)