I am validating request parameters for a rest endpoint as:
@Valid BoundingBox boundingBox
A list of request parameters are mapped to an instance of BoundingBox
.
In class BoundingBox
I have used annotations for field validations, like @Max, @Min etc.
To handle any invalid request parameter, I have overridden
ResponseEntityExceptionHandler.handleMethodArgumentNotValid
method as:
@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex,
HttpHeaders headers, HttpStatus status,
WebRequest request) {
List<String> details = new ArrayList<>();
for(ObjectError error : ex.getBindingResult().getAllErrors()) {
details.add(error.getDefaultMessage());
}
ExceptionDetails error = new ExceptionDetails("Validation Failed", details);
return new ResponseEntity(error, HttpStatus.BAD_REQUEST);
}
Annotation ControllerAdvice
is placed at top of the handler class.
@Valid seems to work as request doesn't pass and returns BAD_REQUEST
, but handleMethodArgumentNotValid
method is not invoked.