Exception Handling in Spring MVC
2015. 5. 12. 04:28 in 3. Implementation/Spring

The following link provides good explanation for exception handling in Spring MVC.
https://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc
In addition, it also provides the sample to demonstrate it.
https://github.com/paulc4/mvc-exceptions
I recognized the ResponseStatus annotation is very useful to return abnormal http status.
1 2 3 4 5 6 7 8 9 10 11 12 | @ResponseStatus (value = HttpStatus.NOT_FOUND, reason = "No such order" ) public class OrderNotFoundException extends RuntimeException { /** * Unique ID for Serialized object */ private static final long serialVersionUID = -8790211652911971729L; public OrderNotFoundException(String orderId) { super (orderId + " not found" ); } } |
In the case of using ControllerAdvice, the following code should be considered if you let other exceptions with ResponseStatus annotation be handled as it is.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | @ControllerAdvice public class GlobalExceptionHandlingControllerAdvice { @ExceptionHandler (SupportInfoException. class ) public ModelAndView handleError(HttpServletRequest req, Exception exception) throws Exception { // Rethrow annotated exceptions or they will be processed here instead. if (AnnotationUtils.findAnnotation(exception.getClass(), ResponseStatus. class ) != null ) throw exception; logger.error( "Request: " + req.getRequestURI() + " raised " + exception); ModelAndView mav = new ModelAndView(); mav.addObject( "exception" , exception); mav.addObject( "url" , req.getRequestURL()); mav.addObject( "timestamp" , new Date().toString()); mav.addObject( "status" , 500 ); mav.setViewName( "support" ); return mav; } } |