Spring Rest ErrorHandling @ControllerAdvice / @Valid

前端 未结 3 496
傲寒
傲寒 2020-12-30 03:29

I\'m having trouble when Using @ControllerAdvice and @Valid annotations together in a REST controller.

I have a rest controller dec

3条回答
  •  [愿得一人]
    2020-12-30 04:10

    You are on the right track, but you need to override the handleMethodArgumentNotValid() instead of the handleException() method, e.g.

    @ControllerAdvice
    public class RestErrorHandler extends ResponseEntityExceptionHandler {
    
        @Override
        protected ResponseEntity handleMethodArgumentNotValid(
                MethodArgumentNotValidException exception,
                HttpHeaders headers,
                HttpStatus status,
                WebRequest request) {
    
            LOG.error(exception);
            String bodyOfResponse = exception.getMessage();
            return new ResponseEntity(errorMessage, headers, status);
        }
    }
    
    
    

    From the JavaDoc of MethodArgumentNotValidException:

    Exception to be thrown when validation on an argument annotated with @Valid fails.

    In other words, a MethodArgumentNotValidException is thrown when the validation fails. It is handled by the handleMethodArgumentNotValid() method provided by the ResponseEntityExceptionHandler, that needs to be overridden if you would like a custom implementation.

    提交回复
    热议问题