Search code examples
javaspringspring-bootspring-mvcbean-validation

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


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?


Solution

  • 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.