Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

spring mvc validation exceptions are not handled by ControllerAdvice

I have a controller in spring boot application, which validate the input using Hibernate Validator. When ever I call the rest endpoint, it validate correctly, but my controller advice doesn't catch it, to customise the message. We only get 404 code with empty payload.

@RestController
public class Controller {

    @RequestMapping(method = RequestMethod.POST, path = RestPaths.LOAD_DATA)
    public void loadCostCenterData(@RequestBody @Valid ClientDto dto) {
    }
}

@RestControllerAdvice
public class WickesGlobalExceptionMapper extends ResponseEntityExceptionHandler {

    @ExceptionHandler(Exception.class)
    public ResponseEntity handleOtherUnexpectedException(Exception ex, WebRequest request) {
    }

}
like image 336
krmanish007 Avatar asked Aug 04 '26 21:08

krmanish007


1 Answers

Here is a working ControllerAdvise that uses ModelView instead of ResponseEntity:

@ControllerAdvice
public class WickesGlobalExceptionMapper {

  @ExceptionHandler(IllegalArgumentException.class)
  @ResponseStatus(HttpStatus.BAD_REQUEST)
  public ModelAndView handleInvalidArgument(IllegalArgumentException ex) {
    ModelAndView modelAndView = new ModelAndView();
    modelAndView.setView(new MappingJackson2JsonView());
    modelAndView.addObject("errorMessage", format("{0}", errorMessage));
    return modelAndView;
  }
}
like image 64
Rlarroque Avatar answered Aug 06 '26 11:08

Rlarroque