0

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 Answer 1

2

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;
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, are there any solutions for when both controllers are annotated with Controller.class?
Yes, then you need to create to different package for api and html requests. Ex. @ControllerAdvice(basePackages="my.api.package") and @ControllerAdvice(basePackages=" "my.html.request.package").

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.