新建ResponseEntityExceptionHandler的继承类:(依然,需要入口类扫描)
/** * @author sky * @version 1.0 */ @ControllerAdvice public class GlobalExceptionHandler extends ResponseEntityExceptionHandler { public static final String DEFAULT_ERROR_VIEW = "exception"; @ExceptionHandler(value = Exception.class) @ResponseBody public Object handleOtherExceptions(final Exception exception, final HttpServletRequest request) { if(isAjaxRequest(request)) { return JSON.toJSONString(“这里是你需要返回的错误json信息”); }else{ ModelAndView mav = new ModelAndView(); mav.addObject("exception", exception); mav.addObject("url", request.getRequestURL()); mav.setViewName(DEFAULT_ERROR_VIEW); return mav; } } /** * isAjaxRequest:判断请求是否为Ajax请求. <br/> * * @param request 请求对象 * @return boolean * @since JDK 1.6 */ public boolean isAjaxRequest(HttpServletRequest request){ String header = request.getHeader("x-requested-with"); if (null != header && "XMLHttpRequest".endsWith(header)) { return true; } return false; } }
这里需要注意,springboot默认读取static下的静态资源,如需要使用templates下的,需要使用thymeleaf
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
exception.html
<!DOCTYPE html> <html xmlns:th="http://www.w3.org/1999/xhtml"> <head lang="en"> <meta charset="UTF-8" /> <title>异常处理</title> </head> <body> <h1>Error Handler</h1> <div th:text="'请求路径:' + ${url}"></div> <div th:text="'异常信息:' + ${exception.message}"></div> </body> </html>
测试异常:
@RequestMapping(value = "/", produces = "text/plain;charset=UTF-8") ModelAndView index(Date date) throws Exception { ModelAndView mav = new ModelAndView(); mav.setViewName("demo1"); if (date == null) { throw new Exception("测试异常"); } return mav; }