Actix Web JsonConfig से JSON त्रुटियाँ अनुकूलित करें
Actix Web का web::Json<T JSON को प्रकार में deserialize करता है और handler चलने से पहले विफलता अस्वीकार करता है। web::JsonConfig body सीमा और custom error handler तय करता है। उदाहरण Actix Web 4.19.0 के लिए है।
Actix Web का web::Json JSON को प्रकार में deserialize करता है और handler चलने से पहले विफलता अस्वीकार करता है। web::JsonConfig body सीमा और custom error handler तय करता है। उदाहरण Actix Web 4.19.0 के लिए है।
Configure the JSON extractor
यह config इस route का body 4096 byte तक सीमित करता है। error handler JsonPayloadError का HTTP status बनाए रखते हुए parser विवरण को स्थिर JSON code से बदलता है। handler वैध input लौटाता है, संग्रहीत नहीं करता। डिफ़ॉल्ट: गलत JSON या अनुपयुक्त Content-Type पर 400, सीमा पार body पर 413; पढ़ने की त्रुटि मूल status का पालन करती है।
[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 चलाएँ। Content-Type: application/json और {"name":"Notes"} के साथ http://127.0.0.1:8080/projects पर POST भेजें। अपेक्षित 201 और {"name":"Notes"}। गलत JSON पर 400, 4096 byte से बड़ी body पर 413; दोनों में {"code":"invalid_request"}। चलाया या compile नहीं किया।
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)