新建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; }
在使用过程中还发现其他问题:比如MissingServletRequestParameterException的错误并不会如同SpringMVC架构一样返回异常信息,直接是没有返回(当然这不排除是自己不熟的问题)
没有返回的原因,预计是框架吃掉了异常,可参考
先说为什么会出现这样的异常呢,比如在你的控制层参数中加入了注解@RequestParam,request为true(默认)的话,而请求又没有传这个参的话,就会发生错误。
这时候,想要自定义全局捕获是不行的,以为会报:模糊不清的启动错误,查出来是因为ResponseEntityExceptionHandler 中存在实现这个异常的捕获。所以多注册一个会报异常
所以直接重构吧(ResponseEntity返回类型可自定义)
@Override protected ResponseEntity<Object> handleMissingServletRequestParameter(MissingServletRequestParameterException ex, HttpHeaders headers, HttpStatus status, WebRequest request) { JSONMessageResponse error = SystemResultUtil.error(5005, "缺少必要参数,参数名称为" + ex.getParameterName()); return new ResponseEntity<>(error, HttpStatus.BAD_REQUEST); }