3

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.

dkackman
  • 15,179
  • 13
  • 69
  • 123
Mandroid
  • 6,200
  • 12
  • 64
  • 134

2 Answers2

0

This response is based on the assumption that a request body was not specified.

In that case, handleMethodArgumentNotValid method will not be called, instead, the handleHttpMessageNotReadable method in the ResponseEntityExceptionHandler class would be called which would return a body of value null.

protected ResponseEntity<Object> handleHttpMessageNotReadable(
        HttpMessageNotReadableException ex, HttpHeaders headers, HttpStatus 
        status, WebRequest request) {

    return handleExceptionInternal(ex, null, headers, status, request);
}

You can provide a custom behavior using the code sample below

@ControllerAdvice
public class CustomizedResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {
    @Override
    protected ResponseEntity<Object> 
          handleHttpMessageNotReadable(HttpMessageNotReadableException ex, 
          HttpHeaders headers, HttpStatus status, WebRequest request) {
        Map<String, Object> response = new HashMap<>();
        response.put("message", "Required request body is missing");

        return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST);
    }
}

The above would return the object below with a 400 status code.

{ "message": "Required request body is missing" }
0

A possible cause could be that you extended ResponseEntityExceptionHandler in another class other than the one you expect the response from. Check your other Exception classes and confirm.

Enock Lubowa
  • 679
  • 8
  • 12