Настройте ошибки JSON через JsonConfig в Actix Web
web::Json<T в Actix Web десериализует JSON и отклоняет ошибки до вызова обработчика. web::JsonConfig задаёт лимит тела и пользовательский обработчик ошибок. Пример для Actix Web 4.19.0.
web::Json в Actix Web десериализует JSON и отклоняет ошибки до вызова обработчика. web::JsonConfig задаёт лимит тела и пользовательский обработчик ошибок. Пример для Actix Web 4.19.0.
Configure the JSON extractor
Конфигурация ограничивает тело маршрута 4096 байтами. Обработчик сохраняет HTTP-статус JsonPayloadError и заменяет детали парсера постоянным 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. Отправьте POST с {"name":"Notes"} и Content-Type: application/json на http://127.0.0.1:8080/projects. Ожидаются 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)