How can I access the request object when handling a MethodArgumentNotValidException?

Viewed 744

I'm handling a MethodArgumentNotValidException thrown after a failed validation of a request object. All the usual stuff is in place: @Valid, @ControllerAdvice, and an extended ResponseEntityExceptionHandler, in which I override handleMethodArgumentNotValid().

As it happens, I need to access that same request object in order to form a customized error response. One way would be to intercept the request before it hits the controller and create a @RequestScope bean with the needed fields in case validation fails later.

Is there a better way?

2 Answers

Thanks to a suggestion from a colleague, I've found that the BindingResult within MethodArgumentNotValidException has a method named getTarget() that returns the validated object. As seen from the method signature (Object getTarget()), the return value needs a cast.

You should have the error fields in the MethodArgumentNotValidException class. Your handleMethodArgumentNotValid function might look like something as follows.

@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
@ResponseBody
public CustomInputErrorResponse handleMethodArgumentNotValid(MethodArgumentNotValidException e) {
    String message = "Invalid inputs";
    ArrayList<String> fieldNames = new ArrayList<String>();
    for (FieldError fieldError : e.getBindingResult().getFieldErrors()) {
        fieldNames.add(fieldError.getField());
    }
    return new CustomInputErrorResponse(message, fieldNames);
}

Considering you have a CustomInputErrorResponse class that takes two arguments for a custom message and error field names.

Related