Common exception handling across controllers

Controller advice can also be used to implement common exception handling across controllers.

Take a look at the following code:

    @ControllerAdvice 
public class ExceptionController {
private Log logger =
LogFactory.getLog(ExceptionController.class);
@ExceptionHandler(value = Exception.class)
public ModelAndView handleException
(HttpServletRequest request, Exception ex) {
logger.error("Request " + request.getRequestURL()
+ " Threw an Exception", ex);
ModelAndView mav = new ModelAndView();
mav.addObject("exception", ex);
mav.addObject("url", request.getRequestURL());
mav.setViewName("common/spring-mvc-error");
return mav;
}
}

Some things to note are as follows:

  • @ControllerAdvice: Controller Advice, by default, is applicable to all controllers.
  • @ExceptionHandler(value = Exception.class): Any method with this annotation will be called when an exception of the type or the sub-type of the class specified(Exception.class) is thrown in the controllers.
  • public ModelAndView handleException (HttpServletRequest request, Exception ex): The exception that is thrown is injected into the Exception variable. The method is declared with a ModelAndView return type to be able to return a model with the exception details and an exception view.
  • mav.addObject("exception", ex): Adding the exception to the model so that the exception details can be shown in the view.
  • mav.setViewName("common/spring-mvc-error"): The exception view.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset