Actix Web の JsonConfig で JSON エラーを整える
Actix Web の web::Json<T は JSON を型にデシリアライズし、失敗するとハンドラー実行前に拒否します。web::JsonConfig で本文上限と独自エラーハンドラーを設定できます。Actix Web 4.19.0 の例です。
Actix Web の web::Json は JSON を型にデシリアライズし、失敗するとハンドラー実行前に拒否します。web::JsonConfig で本文上限と独自エラーハンドラーを設定できます。Actix Web 4.19.0 の例です。
Configure the JSON extractor
この設定はルートの本文を4096バイトに制限します。エラーハンドラーは JsonPayloadError の HTTP ステータスを保ち、パーサー詳細を安定した JSON コードに置き換えます。有効な入力は保存せず返します。既定では不正 JSON または不適切な Content-Type は400、上限超過は413、読み取りエラーは基になる状態に従います。
[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バイト超は413で、どちらも{"code":"invalid_request"}。未コンパイル・未実行です。
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)