1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
//! Handlers to manage HTTP responses.
use crateValidationErrorPayload;
use InternalError;
use ;
use Error;
/// Function to handle validation errors when serializing the request payload (JSON body),
/// or the query string, generating a HTTP 400 error with a JSON body
/// describing the error. It has to be configured with the [`JsonConfig`](https://docs.rs/actix-web-validator/latest/actix_web_validator/struct.JsonConfig.html)
/// extractor from the [actix-web-validator](https://docs.rs/actix-web-validator) validator crate.
/// # Example
/// Configure the method as follow:
/// ```
/// use actix_web::{web, App};
/// use actix_web::HttpResponse;
/// use actix_web::Responder;
/// use actix_web_validator::{Json, JsonConfig};
/// use actix_contrib_rest::response::json_error_handler;
/// use serde::Deserialize;
/// use validator::Validate;
///
/// #[derive(Deserialize, Validate)]
/// pub struct FormPayload {
/// #[validate(length(min = 3, max = 50))]
/// pub name: String,
/// // ...
/// }
///
/// async fn post_handler(form: Json<FormPayload>) -> impl Responder {
/// // ...
/// HttpResponse::Ok()
/// }
///
/// fn main() {
/// let app = App::new().service(
/// web::resource("/api")
/// // ...
/// .app_data(JsonConfig::default().error_handler(json_error_handler))
/// .route(web::post().to(post_handler))
/// );
/// }
/// ```
/// If there is an error in the validations, the response will look like:
/// ```json
/// {
/// "error": "Validation error",
/// "field_errors": {
/// "name": [
/// {
/// "code": "length",
/// "message": null,
/// "params": {
/// "max": 50,
/// "min": 3,
/// "value": "Bi"
/// }
/// }
/// ]
/// }
/// }
/// ```