The annotation @ExceptionHandler can be used on methods of @Controller classes. One of these methods is invoked when an specified exception thrown by a @RequestMapping method. The method can return a view name or a message body by using @ResponseBody.
@RequestMapping("/data/{year}") @ResponseBody public String handleRequest(@PathVariable("year") int year) throws Exception { if (Year.of(year).isBefore(Year.of(1990))) { throw new Exception("Year is before 1990: " + year); } return "data response " + year; }
@RequestMapping("/test/{id}") @ResponseBody public String handleRequest2(@PathVariable("id") String id) { int i = Integer.parseInt(id); return "test response " + i; }
@RequestMapping("/admin") @ResponseBody public String handleRequest3(HttpServletRequest request) throws UserNotLoggedInException {
Object user = request.getSession() .getAttribute("user"); if (user == null) { throw new UserNotLoggedInException("user: " + user); } return "test response " + user; }
@ExceptionHandler(NumberFormatException.class) public ModelAndView exceptionHandler(NumberFormatException re) { ModelAndView mav = new ModelAndView("errorPage"); mav.addObject("exception", re); return mav; }
/** * This will throw MissingPathVariableException with response code 500 */ @RequestMapping("/test/{id}") @ResponseBody public String handleRequest (@PathVariable("testId") String id) { return "id: "+id; }
/** * The exception should be processed by @ExceptionHandler method */ @RequestMapping("/test") public String handleRequest2 () throws Exception { throw new IllegalStateException(); }
@ExceptionHandler @ResponseBody public String handleException (IllegalStateException b) { return "from @ExceptionHandler method: " + b ; } }