Sesuaikan kesalahan JSON dengan JsonConfig Actix Web
web::Json<T Actix Web mendeserialisasi JSON dan menolak kegagalan sebelum handler berjalan. web::JsonConfig mengatur batas payload dan penangan kesalahan khusus. Contoh memakai Actix Web 4.19.0.
web::Json Actix Web mendeserialisasi JSON dan menolak kegagalan sebelum handler berjalan. web::JsonConfig mengatur batas payload dan penangan kesalahan khusus. Contoh memakai Actix Web 4.19.0.
Configure the JSON extractor
Konfigurasi membatasi body rute ini hingga 4096 byte. Penangan mempertahankan status HTTP JsonPayloadError dan mengganti detail parser dengan kode JSON tetap. Input valid dikembalikan tanpa disimpan. Default: JSON salah atau Content-Type tidak diterima menghasilkan 400; body terlalu besar 413; kesalahan baca mengikuti status dasarnya.
[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
Jalankan cargo run. Kirim POST dengan {"name":"Notes"} dan Content-Type: application/json ke http://127.0.0.1:8080/projects. Hasil yang diharapkan 201 dan {"name":"Notes"}. JSON salah: 400; body lebih dari 4096 byte: 413; keduanya memakai {"code":"invalid_request"}. Tidak dikompilasi atau dijalankan.
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)