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.now().isAfter(Year.of(year))) { throw new Exception("Year is not before current year: " + 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 handleRequest2 (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 String exceptionHandler (NumberFormatException re, Model model) { model.addAttribute("exception", re); return "errorPage"; }
@ResponseStatus(HttpStatus.BAD_REQUEST) @ExceptionHandler(Exception.class) @ResponseBody public String exceptionHandler2 (Exception re, Model model) { System.out.println(model); return "Exception: " + re.getMessage(); }
@ResponseStatus(HttpStatus.FORBIDDEN) @ExceptionHandler(UserNotLoggedInException.class) public String exceptionHandler3 (UserNotLoggedInException e, Model model) { model.addAttribute("exception", e); return "errorPage"; } }
/** * 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 OperationNotSupportedException(); }
@ExceptionHandler @ResponseBody public String handleException (OperationNotSupportedException b) { return "from @ExceptionHandler method: " + b ; } }