How to write a proper global error handler with Spring MVC / Spring Boot

前端 未结 1 2027
慢半拍i
慢半拍i 2020-12-04 13:13

I\'m writing a web application with Spring 4.0.4 and Spring Boot 1.0.2 using Tomcat as embedded web container and I want to implement a global exception handling which inter

相关标签:
1条回答
  • 2020-12-04 13:40

    Have a look at ControllerAdvice You could do something like this:

    @ControllerAdvice
    public class ExceptionHandlerController {
    
        public static final String DEFAULT_ERROR_VIEW = "error";
    
        @ExceptionHandler(value = {Exception.class, RuntimeException.class})
        public ModelAndView defaultErrorHandler(HttpServletRequest request, Exception e) {
                ModelAndView mav = new ModelAndView(DEFAULT_ERROR_VIEW);
    
            mav.addObject("datetime", new Date());
            mav.addObject("exception", e);
            mav.addObject("url", request.getRequestURL());
            return mav;
        }
    }
    
    0 讨论(0)
提交回复
热议问题