用 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。向 http://127.0.0.1:8080/projects 傳送含 {"name":"Notes"} 且 Content-Type: application/json 的 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)