Spring Rest ErrorHandling @ControllerAdvice / @Valid
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<Object> 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.
Better format of return message:
@ControllerAdvice
public class MyControllerAdvice extends ResponseEntityExceptionHandler {
@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(
MethodArgumentNotValidException ex,
HttpHeaders headers,
HttpStatus status,
WebRequest request) {
BindingResult result = ex.getBindingResult();
List<FieldErrorVM> fieldErrors = result.getFieldErrors().stream()
.map(f -> new FieldErrorVM(f.getObjectName(), f.getField(), f.getCode()))
.collect(Collectors.toList());
return handleExceptionInternal(ex, "Method argument not valid, fieldErrors:" + fieldErrors ,new HttpHeaders(), HttpStatus.BAD_REQUEST, request);
}
}