用 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)