简体   繁体   中英

Documentation of Spring Validation Errors

Spring, als always, provides very useful defaults to handle Validation errors. But sometimes it looks difficult to customize those. In my case I have a custom validation that uses a javascript function to validate a field in a domain object. The default validation error produces 4 message codes that use the object name, the field name, the field type and the validation type. So far so good. But I would like to add an additional code that contains the name of the js-function as a component. How could I do that?

Or more general my question is: where do I find a documentation of the way Spring builds the default error messages, and how they can be manipulated.

In my case I get an output like:

{
  "timestamp": 1457092927829,
  "status": 400,
  "error": "Bad Request",
  "exception": "org.springframework.web.bind.MethodArgumentNotValidException",
  "errors": [
    {
      "codes": [
        "JSValidated.order.validFrom",
        "JSValidated.validFrom",
        "JSValidated.java.time.ZonedDateTime",
        "JSValidated"
      ],
      "arguments": [
        {
          "codes": [
            "order.validFrom",
            "validFrom"
          ],
          "arguments": null,
          "defaultMessage": "validFrom",
          "code": "validFrom"
        },
        "checkOrder",
        "static/OrderValidator.js"
      ],
      "defaultMessage": "validation checkValidFrom failed",
      "objectName": "order",
      "field": "validFrom",
      "rejectedValue": 1196586930,
      "bindingFailure": false,
      "code": "JSValidated"
    },
    {
      "codes": [
        "NotEmpty.order.id",
        "NotEmpty.id",
        "NotEmpty.java.lang.String",
        "NotEmpty"
      ],
      "arguments": [
        {
          "codes": [
            "order.id",
            "id"
          ],
          "arguments": null,
          "defaultMessage": "id",
          "code": "id"
        }
      ],
      "defaultMessage": "may not be empty",
      "objectName": "order",
      "field": "id",
      "rejectedValue": null,
      "bindingFailure": false,
      "code": "NotEmpty"
    }
  ],
  "message": "Validation failed for object='order'. Error count: 2",
  "path": "/order"
}

How can I add or change the codes? How can I add or change the list of arguments? Where is all the stuff documented?

You can use a global exception handler using @ExceptionHandler You can define which exceptions should be handled. You have access to the thrown exception, which contains also the validation errors. Create your own error class, that contains the properties you want to return. Map the validation error into your error object and return it along with the HTTP status of your choice. BindingException is one Exception I got from validation and the handler looks like this :

@ExceptionHandler(BindException.class)
@ResponseBody
public ResponseEntity<Object> handle(HttpServletRequest req, BindException ex) {        
    ExceptionResponse response = new ExceptionResponse(ex);
    return new ResponseEntity<>(response, HttpStatus.EXPECTATION_FAILED);
}

And the error class ExceptionResponse :

@JsonInclude(Include.NON_NULL)
@JsonAutoDetect(fieldVisibility = Visibility.ANY, getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE)
public static class ExceptionResponse{
String exception;
String message;
String trace;
public ExceptionResponse(Exception exception) {
    super();
    this.exception = exception.getClass().getName();
    this.message = exception.getMessage();
    this.trace = Arrays.toString(exception.getStackTrace());
}

This is a json serialization of the result of method getErrorAttributes(RequestAttributes requestAttributes, boolean includeStackTrace) of class org.springframework.boot.autoconfigure.web.DefaultErrorAttributes .

This class can be extended to add additional properties.

Codes and messages are added by validators, do if you'd like to change them you need to customize validators used.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM