I-customize ang JSON error gamit ang Actix Web JsonConfig
Dini-deserialize ng Actix Web web::Json<T ang JSON at tinatanggihan ang failure bago tumakbo ang handler. Itinatakda ng web::JsonConfig ang body limit at custom error handler. Para ito sa Actix Web 4.19.0.
Dini-deserialize ng Actix Web web::Json ang JSON at tinatanggihan ang failure bago tumakbo ang handler. Itinatakda ng web::JsonConfig ang body limit at custom error handler. Para ito sa Actix Web 4.19.0.
Configure the JSON extractor
Nililimitahan ng config ang body ng route sa 4096 byte. Pinananatili ng error handler ang HTTP status ng JsonPayloadError at pinapalitan ang detalye ng parser ng matatag na JSON code. Ibinabalik ng handler ang valid na input ngunit hindi ito sine-save. Default: invalid JSON o Content-Type ay 400, sobrang laki ay 413; sinusunod ng read error ang status ng pinagbabatayang error.
[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
Patakbuhin ang cargo run. Mag-POST ng {"name":"Notes"} na may Content-Type: application/json sa http://127.0.0.1:8080/projects; inaasahan ang 201 at {"name":"Notes"}. Invalid JSON: 400; lampas 4096 byte: 413; kapwa may {"code":"invalid_request"}. Hindi na-compile o pinatakbo.
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)