Actix Web JsonConfig ile JSON hatalarını özelleştirin
Actix Web web::Json<T, JSON’u türe dönüştürür ve hata olursa handler çalışmadan reddeder. web::JsonConfig gövde sınırını ve özel hata işleyicisini ayarlar. Örnek Actix Web 4.19.0 içindir.
Actix Web web::Json, JSON’u türe dönüştürür ve hata olursa handler çalışmadan reddeder. web::JsonConfig gövde sınırını ve özel hata işleyicisini ayarlar. Örnek Actix Web 4.19.0 içindir.
Configure the JSON extractor
Yapılandırma bu rotanın gövdesini 4096 baytla sınırlar. Hata işleyicisi JsonPayloadError HTTP durumunu korur ve ayrıştırıcı ayrıntılarını sabit JSON koduyla değiştirir. Geçerli girdi saklanmadan geri döndürülür. Varsayılan olarak hatalı JSON veya Content-Type 400, sınır aşımı 413; okuma hatası alt hatanın durumunu izler.
[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 çalıştırın. Content-Type: application/json ve {"name":"Notes"} ile http://127.0.0.1:8080/projects adresine POST gönderin. Beklenen 201 ve {"name":"Notes"}. Hatalı JSON 400, 4096 baytı aşan gövde 413 döndürür; ikisi de {"code":"invalid_request"} kullanır. Derlenmedi veya çalıştırılmadı.
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)