🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
[TOC] # SpringBoot 默认的异常处理机制 默认情况下 SpringBoot 为两种情况提供了不同的响应方式, * 一种是浏览器客户端请求一个不存在的地址, * 另一种是服务端内部发生错误。 不管这两种情况哪一种发生,SpringBoot 都会访问`/error`地址返回对应信息,在访问`/error`时,根据 Headers 请求头中的`Accept`值进行判断, 如果是`Accept: text/html`则判断为网页访问,这样将会根据状态码返回对应的 HTML 错误页面。 如果 Headers 请求头中不存在`Accept`属性或者的值不为`text/html`,那么将会返回一个包含错误信息的 JSON 对象 SpringBoot 中默认异常处理源码 BasicErrorController 类,里面包含了 SpringBoot 默认异常处理逻辑,源码如下: BasicErrorController 类在 SpringBoot 官方 Github 地址为:[BasicErrorController.java](https://github.com/spring-projects/spring-boot/blob/master/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/error/BasicErrorController.java) ~~~ @Controller @RequestMapping({"${server.error.path:${error.path:/error}}"}) public class BasicErrorController extends AbstractErrorController { ...... public String getErrorPath() { return this.errorProperties.getPath(); } /** * 根据状态码,返回对应 HTML 错误页面。 */ @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); } /** * 使用 JSON 返回错误信息。 */ @RequestMapping 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); } ...... } ~~~