0
votes

I am using Spring Boot 1.5.7. I have an ExceptionHandler for my exception that returns a ResponseEntity

@ExceptionHandler(MyException.class)
public ResponseEntity<ResponseExceptionEntity> handleException(MyException e) {
    return ResponseEntity
        .status(HttpStatus.BAD_REQUEST)
        .body(new ResponseExceptionEntity(e));
}     

This works well in situations where the exception occurs during an api call returning a ResponseEntity / @ResponseBody (JSON/XML response)

I would like to return a ModelAndView in situations where the exception occurs during a request where HTML is returned. In my situation all Controllers are annotated with @Controller and not @RestController

  • how can I write a ExceptionHandler for both cases (api/html)?
  • Or How can I determine what the resolved view is for a controller method?
  • Or how can I determine what the return type of the Controller Method is?
  • Or How can I determine what the resolved view is for the controller method?

I've tried the suggestion in this answer, but it doesn't return a JSON response when the Controller Method is annotated with @ResponseBody.

https://stackoverflow.com/a/32071252/461055

1

1 Answers

3
votes

Yes, you can write two exception handler to handle api and html request exception. Here is sample code to illustrate the solution.

@ControllerAdvice(annotations = RestController.class)
@Order(1)
class RestExceptionHandler {
    @ExceptionHandler(MyException.class)
    @ResponseBody
    ResponseEntity<ErrorResponse> exceptionHandler() {
        ....
    }
}

@ControllerAdvice(annotations = Controller.class)
@Order(2)
class ExceptionHandler {
    @ExceptionHandler(Exception.class)
    public ModelAndView handleError500(HttpServletRequest request, HttpServletResponse response, Exception ex) {
        ModelAndView mav = new ModelAndView("error");
        mav.addObject("error", "500");
        return mav;
    }
}