主要介绍 @ControllerAdvice 注解方式
代码:
@ControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(Exception.class) public ModelAndView globalHandler(HttpServletRequest request, HttpServletResponse response, Exception ex) { ModelAndView mv = new ModelAndView(new MappingJackson2JsonView()); if (!isAnsynJsonRequest(request)) { mv = new ModelAndView("error/500"); } mv.addObject("code", 500); mv.addObject("msg", "系统异常"); mv.addObject("message", ex.getMessage()); mv.addObject("detail", ex.getClass().getName()); mv.addObject("cause root", ex.getStackTrace()[0]); return mv; } private boolean isAnsynJsonRequest(HttpServletRequest request) { return request.getRequestURI().contains("/api") || request.getHeader("accept").contains("application/json") || (request.getHeader("X-Requested-With") != null && request .getHeader("X-Requested-With").contains( "XMLHttpRequest")); } }
其中 isAnsynJsonRequest 方法用于判断当前请求是否是异步或者是 /api路径(一般api只返回数据不返回页面)
error/500是 WEB-INF/目录下的错误页面的路径