Dostosuj błędy JSON za pomocą JsonConfig w Actix Web
web::Json<T w Actix Web deserializuje JSON i odrzuca błędy przed uruchomieniem handlera. web::JsonConfig ustawia limit treści i własną obsługę błędów. Przykład dla Actix Web 4.19.0.
web::Json w Actix Web deserializuje JSON i odrzuca błędy przed uruchomieniem handlera. web::JsonConfig ustawia limit treści i własną obsługę błędów. Przykład dla Actix Web 4.19.0.
Configure the JSON extractor
Konfiguracja ogranicza treść tej trasy do 4096 bajtów. Handler zachowuje status HTTP JsonPayloadError i zastępuje szczegóły parsera stałym kodem JSON. Poprawne wejście zwraca bez zapisu. Domyślnie błędny JSON lub Content-Type daje 400, przekroczenie limitu 413; błąd odczytu zachowuje status błędu źródłowego.
[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
Uruchom cargo run. Wyślij POST z {"name":"Notes"} i Content-Type: application/json do http://127.0.0.1:8080/projects. Oczekiwane 201 i {"name":"Notes"}. Błędny JSON: 400, ponad 4096 bajtów: 413; oba z {"code":"invalid_request"}. Nie kompilowano ani nie uruchamiano.
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)