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

Get Mastering Spring 5.0 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.