我正在使用Tomcat作为嵌入式Web容器使用Spring 4.0.4和Spring Boot 1.0.2编写Web应用程序,我想实现一个全局异常处理,该处理将拦截所有异常并以特定方式记录它们。我的简单要求是:
到目前为止,我的解决方案如下所示(简化,无日志记录,无重定向到错误视图):
@Controller @RequestMapping("/errors") public class ErrorHandler implements EmbeddedServletContainerCustomizer { @Override public void customize(final ConfigurableEmbeddedServletContainer factory) { factory.addErrorPages(new ErrorPage("/errors/unexpected")); factory.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/errors/notfound")); } @RequestMapping("unexpected") @ResponseBody public String unexpectedError(final HttpServletRequest request) { return "Exception: " + request.getAttribute("javax.servlet.error.exception"); } @RequestMapping("notfound") @ResponseBody public String notFound() { return "Error 404"; } }
结果是该unexpectedError方法正确处理了抛出在控制器中的异常,该方法正确处理了404状态码notFound。到目前为止,还不错,但是我有以下问题:
unexpectedError
notFound
javax.servlet.error.exception
org.springframework.web.util.NestedServletException
那么我该如何解决这些问题呢?还是我实现此全局异常处理程序的方式是完全错误的,并且有更好的选择?
看看ControllerAdvice,您可以执行以下操作:
@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; } }