Customize JSON errors with Actix Web JsonConfig
Actix Web web::Json<T deserializes JSON into a type and rejects failures before the handler runs. web::JsonConfig sets a payload limit and custom error handler. This example uses Actix Web 4.19.0.
Actix Web web::Json deserializes JSON into a type and rejects failures before the handler runs. web::JsonConfig sets a payload limit and custom error handler. This example uses Actix Web 4.19.0.
Configure the JSON extractor
The config caps this route’s body at 4096 bytes. Its error handler keeps JsonPayloadError’s HTTP status and replaces parser details with a stable JSON code. The handler echoes valid input; it does not persist it. Defaults: malformed JSON or unacceptable Content-Type returns 400; an oversized body returns 413; payload-read errors follow the underlying error status.
[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
Run cargo run. POST {"name":"Notes"} to http://127.0.0.1:8080/projects with Content-Type: application/json; expected 201 and {"name":"Notes"}. Invalid JSON should return 400 and a body over 4096 bytes 413; both use {"code":"invalid_request"}. Not compiled or run.
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)