3. Implementation/Spring
Exception Handling in Spring MVC
SSKK
2015. 5. 12. 04:28
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.
@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.
@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; } }