您处在正确的轨道上,但是您需要覆盖handleMethodArgumentNotValid()而不是
handleException()方法,例如
@ControllerAdvicepublic class RestErrorHandler extends ResponseEntityExceptionHandler { @Override protected ResponseEntity<Object> handleMethodArgumentNotValid( MethodArgumentNotValidException exception, HttpHeaders headers, HttpStatus status, WebRequest request) { LOG.error(exception); String bodyOfResponse = exception.getMessage(); return new ResponseEntity(errorMessage, headers, status); }}从MethodArgumentNotValidException的JavaDoc中:
当对用@Valid注释的参数进行验证失败时,将引发异常。
换句话说,
MethodArgumentNotValidException验证失败时将引发a
。它由所
handleMethodArgumentNotValid()提供的方法处理,
ResponseEntityExceptionHandler如果您想要自定义实现,则需要重写该方法。



