How do I customize default error message from spring @Valid validation?

前端 未结 10 858
孤街浪徒
孤街浪徒 2020-12-22 23:04

DTO:

public class User {

    @NotNull
    private String name;

    @NotNull
    private String password;

    //..
}

Controller:

10条回答
  •  粉色の甜心
    2020-12-22 23:33

    For customized the error message in JSON format then do the below steps.

    - Create one @Component called CommonErrorHandler

    @Component
    public class CommonErrorHandler {
    public  Map getFieldErrorResponse(BindingResult result){
    
            Map fielderror = new HashMap<>();
            Listerrors= result.getFieldErrors();
            for (FieldError error : errors) {
                fielderror.put(error.getField(), error.getDefaultMessage());
            }return fielderror;
        }
    
         public ResponseEntity fieldErrorResponse(String message,Object fieldError){
            Map map = new HashMap<>();
            map.put("isSuccess", false);
            map.put("data", null);
            map.put("status", HttpStatus.BAD_REQUEST);
            map.put("message", message);
            map.put("timeStamp", DateUtils.getSysDate());
            map.put("filedError", fieldError);
            return new ResponseEntity(map,HttpStatus.BAD_REQUEST);
        }
    }
    
    
    

    -- Add InvalidException class

    public class InvalidDataException extends RuntimeException {
    
    /**
     * @author Ashok Parmar
     */
        private static final long serialVersionUID = -4164793146536667139L;
    
        private BindingResult result;
    
        public InvalidDataException(BindingResult result) {
            super();
            this.setResult(result);
        }
    
        public BindingResult getResult() {
            return result;
        }
    
        public void setResult(BindingResult result) {
            this.result = result;
        }
    
    }
    

    - Introduce @ControllerAdvice class

    @ControllerAdvice
    public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
    
    @ExceptionHandler(InvalidDataException.class)
        public ResponseEntity invalidDataException(InvalidDataException ex, WebRequest request) {
    
            List errors = ex.getResult().getFieldErrors();
            for (FieldError error : errors) {
                logger.error("Filed Name ::: " + error.getField() + "Error Message :::" + error.getDefaultMessage());
            }
            return commonErrorHandler.fieldErrorResponse("Error", commonErrorHandler.getFieldErrorResponse(ex.getResult()));
        }
        }
    

    -- Use in controller with @Valid and throw exception

    public AnyBeans update(**@Valid** @RequestBody AnyBeans anyBeans ,
                BindingResult result) {
            AnyBeans resultStr = null;
            if (result.hasErrors()) {
                **throw new InvalidDataException(result);**
            } else {
                    resultStr = anyBeansService.(anyBeans );
                    return resultStr;
            }
        }
    

    -- Output will be in JSON format

    {
      "timeStamp": 1590500231932,
      "data": null,
      "message": "Error",
      "isSuccess": false,
      "status": "BAD_REQUEST",
      "filedError": {
        "name": "Name is mandatory"
      }
    }
    

    Hope this will be work. :-D

    提交回复
    热议问题