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

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

DTO:

public class User {

    @NotNull
    private String name;

    @NotNull
    private String password;

    //..
}

Controller:

10条回答
  •  礼貌的吻别
    2020-12-22 23:44

    @ControllerAdvice(annotations = RestController.class)
    public class GlobalExceptionHandler implements ApplicationContextAware {
    
        @ExceptionHandler(MethodArgumentNotValidException.class)
        @ResponseStatus(HttpStatus.OK)
        @ResponseBody
        public ApplicationError validationException(MethodArgumentNotValidException e) {
    
            e.printStackTrace();
            return new ApplicationError(SysMessageEnum.MSG_005, e.getBindingResult().getAllErrors().get(0).getDefaultMessage());
    
        }
    
    }
    

提交回复
热议问题