SpringBoot默认异常默认处理机制
Spring boot错误异常时通过BasicErrorController来处理的
通过判断是浏览器请求还是ajax请求响应页面或者json
BasicErrorController部分源码
@RequestMapping( produces = {"text/html"} ) public ModelAndView errorHtml(HttpServletRequest request, HttpServletResponse response) { HttpStatus status = this.getStatus(request); Map<String, Object> model = Collections.unmodifiableMap(this.getErrorAttributes(request, this.isIncludeStackTrace(request, MediaType.TEXT_HTML))); response.setStatus(status.value()); ModelAndView modelAndView = this.resolveErrorView(request, response, status, model); return modelAndView != null ? modelAndView : new ModelAndView("error", model); } @RequestMapping @ResponseBody public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) { Map<String, Object> body = this.getErrorAttributes(request, this.isIncludeStackTrace(request, MediaType.ALL)); HttpStatus status = this.getStatus(request); return new ResponseEntity(body, status); }
可以看到 只要是发生生异常浏览器请求 都会默认返回error页面
覆盖springboot默认异常处理的异常页面
1.在resources/templates 下新增一个error html则可以对默认的error进行覆盖
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> 动态error错误页面 <p th:text="${error}"></p> <p th:text="${status}"></p> <p th:text="${message}"></p> </body> </html>
发生错则打印
2.如果想对异常进行更细的划分 比如404 跳转到404的错误页面 500跳转到500的错误页面
只需要在resources/templates/error 新建对应的编码的页面