SpringBoot——Web开发三(错误处理机制)

    技术2026-04-05  8

    1.SpringBoot默认的错误处理机制

    1.1默认效果

    1.浏览器,会返回一个默认的错误页面

    2.如果是其他客户端,默认响应一个JSON数据

    1.2 原理

    可以参照ErrorMvcAutoConfiguration,错误处理的自动配置,这个给容器中添加了以下组件。

    1.DefaultErrorAttributes

    //帮我们共享信息 public Map<String, Object> getErrorAttributes(WebRequest webRequest, ErrorAttributeOptions options) { Map<String, Object> errorAttributes = this.getErrorAttributes(webRequest, options.isIncluded(Include.STACK_TRACE)); if (this.includeException != null) { options = options.including(new Include[]{Include.EXCEPTION}); } if (!options.isIncluded(Include.EXCEPTION)) { errorAttributes.remove("exception"); } if (!options.isIncluded(Include.STACK_TRACE)) { errorAttributes.remove("trace"); } if (!options.isIncluded(Include.MESSAGE) && errorAttributes.get("message") != null) { errorAttributes.put("message", ""); } if (!options.isIncluded(Include.BINDING_ERRORS)) { errorAttributes.remove("errors"); } return errorAttributes; } /** @deprecated */ @Deprecated public Map<String, Object> getErrorAttributes(WebRequest webRequest, boolean includeStackTrace) { Map<String, Object> errorAttributes = new LinkedHashMap(); errorAttributes.put("timestamp", new Date()); this.addStatus(errorAttributes, webRequest); this.addErrorDetails(errorAttributes, webRequest, includeStackTrace); this.addPath(errorAttributes, webRequest); return errorAttributes; }

    2.BasicErrorController:处理默认/error请求

    @Controller @RequestMapping("${server.error.path:${error.path:/error}}") public class BasicErrorController extends AbstractErrorController

    在其方法中又通过两种方式返回不同的数据(这就是为啥通过浏览器请求返回html,通过其他客户端返回json)

    //产生html类型的属性,浏览器发送的请求来到这个方法处理 @RequestMapping(produces = MediaType.TEXT_HTML_VALUE) public ModelAndView errorHtml(HttpServletRequest request, HttpServletResponse response) { HttpStatus status = getStatus(request); Map<String, Object> model = Collections .unmodifiableMap(getErrorAttributes(request, getErrorAttributeOptions(request, MediaType.TEXT_HTML))); response.setStatus(status.value()); //去哪个页面作为错误页面,包含页面地址和页面内容 ModelAndView modelAndView = resolveErrorView(request, response, status, model); return (modelAndView != null) ? modelAndView : new ModelAndView("error", model); } //产生JSON数据,其他客户端来到这个方法处理; @RequestMapping public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) { HttpStatus status = getStatus(request); if (status == HttpStatus.NO_CONTENT) { return new ResponseEntity<>(status); } Map<String, Object> body = getErrorAttributes(request, getErrorAttributeOptions(request, MediaType.ALL)); return new ResponseEntity<>(body, status); }

    查看浏览器的请求头:

    查看客户端的请求头:

    可以看到这两个对应BasicErrorController处理的两种方式。

    获得所有的ErrorViewResolver,而这个ErrorViewResolver就是下面的DefaultErrorViewResolver组件,去哪个页面就是由它来解析的的,通过DefaultErrorViewResolver组件得知

    protected ModelAndView resolveErrorView(HttpServletRequest request, HttpServletResponse response, HttpStatus status, Map<String, Object> model) { for (ErrorViewResolver resolver : this.errorViewResolvers) { ModelAndView modelAndView = resolver.resolveErrorView(request, status, model); if (modelAndView != null) { return modelAndView; } } return null; }

    3.ErrorPageCustomizer

    @Override public void registerErrorPages(ErrorPageRegistry errorPageRegistry) { ErrorPage errorPage = new ErrorPage( this.dispatcherServletPath.getRelativePath(this.properties.getError().getPath())); errorPageRegistry.addErrorPages(errorPage); } //查看getpath方法,看到path @Value("${error.path:/error}") private String path = "/error";

    4.DefaultErrorViewResolver

    @Override public ModelAndView resolveErrorView(HttpServletRequest request, HttpStatus status, Map<String, Object> model) { ModelAndView modelAndView = resolve(String.valueOf(status.value()), model); if (modelAndView == null && SERIES_VIEWS.containsKey(status.series())) { modelAndView = resolve(SERIES_VIEWS.get(status.series()), model); } return modelAndView; } private ModelAndView resolve(String viewName, Map<String, Object> model) { //默认的SpringBoot可以去找一个页面: error/404 String errorViewName = "error/" + viewName; //模板引擎可以解析这个页面地址就用模板引擎解析 TemplateAvailabilityProvider provider = this.templateAvailabilityProviders.getProvider(errorViewName, this.applicationContext); if (provider != null) { //模板引擎可用的情况下返回errorViewName指定的视图地址 return new ModelAndView(errorViewName, model); } //模板引擎不可用,就在静态资源文件夹下找errorViewName对应的页面 error/404.html return resolveResource(errorViewName, model); } private ModelAndView resolveResource(String viewName, Map<String, Object> model) { for (String location : this.resourceProperties.getStaticLocations()) { try { Resource resource = this.applicationContext.getResource(location); resource = resource.createRelative(viewName + ".html"); if (resource.exists()) { return new ModelAndView(new HtmlResourceView(resource), model); } } catch (Exception ex) { } } return null; }

    步骤:一旦系统出现4xx或者5xx之类的错误,ErrorPageCustomizer就会生效(定制错误的响应规则),就会来到/error请求,这个请求就会被BasicErrorController处理。

    响应页面:去哪个页面是由DefaultErrorViewResolver解析得到的。

    2.如何定制错误响应

    2.1 如何定制错误页面(浏览器)

    1.在由模板引擎的情况下:error/状态码。将错误页面命名为 错误状态码.html放在模板引擎文件夹里面的error文件夹下,发生此状态码的错误就会来到对应的页面。

    我们可以使用4xx和5xx作为错误页面的文件名来匹配这种类型的所有错误,精确优先(优先寻找精确的状态码.html)。如下所示:

    页面能获取的信息(这个信息可以从上面DefaultErrorAttributes源码中看到):

    timestamp:时间戳

    status:状态码

    error:错误提示

    exception:异常对象

    message:异常消息

    errors:JSR303数据校验的错误都在这里

    可以看到html页面取属性:

    <main role="main" class="col-md-9 ml-sm-auto col-lg-10 pt-3 px-4"> <h1>status:[[${status}]]</h1> <h1>timestamp:[[${timestamp}]]</h1> <h1>message:[[${message}]]</h1> <h1>exception:[[${exception}]]</h1> <!--配置文件配置--> </main>

    2.没有模板引擎(模板引擎找不到这个错误页面),静态资源文件夹下找。

    3.以上都没有错误页面,就是默认来到SpringBoot的默认错误提示页面。

    2.2 如何定制错误的JSON数据

    自己先编写一个异常:

    public class UserNotExistException extends RuntimeException{ public UserNotExistException() { super("用户不存在"); } }

    1.自定义异常处理和返回JSON数据,这个没有自适应的效果,也就是没有上面说的时间戳等信息

    @ControllerAdvice public class MyExceptionHandler { //第一种写法,浏览器和客户端返回都是JSON数据 @ResponseBody @ExceptionHandler(UserNotExistException.class) public Map handleException(Exception e){ Map<String,Object> map=new HashMap<>(); map.put("code","user.notexist"); map.put("message",e.getMessage()); return map; } }

    这个原理的就是:我们在看BasicErrorController这个源码的时候(用来处理/error请求),可以看到添加这个组件的时候,就可以看到这个上面有这个注解:

    @ConditionalOnMissingBean(value = ErrorController.class, search = SearchStrategy.CURRENT)

    意思是没有这个ErrorController类的话,这个组件才生效。现在我们自定义了MyExceptionHandler用来处理UserNotExistException异常。

    2.转发到/error请求

    @ExceptionHandler(UserNotExistException.class) public String handleException(Exception e, HttpServletRequest request){ //传入我们自己的错误状态码 4xx 5xx,否则就不会进入定制错误页面的解析流程 /** * Integer statusCode = (Integer) request .getAttribute("javax.servlet.error.status_code"); */ Map<String,Object> map=new HashMap<>(); request.setAttribute("javax.servlet.error.status_code",400); map.put("code","user.notexist"); map.put("message",e.getMessage()); request.setAttribute("ext",map); //转发到/error请求 return "forward:/error"; }

    3.将定制的数据携带出去

    出现错误以后,会来到/error请求,会被BasicErrorController处理,响应出去可以获取的数据是由getErrorAttributes得到的(是AbstractErrorController(ErrorController)规定的方法)。

    1.完全来编写ErrorController的实现类(或者是编写AbstractErrorController的子类),放在容器中。

    2.页面上用的数据,或者是JSON返回能用的数据都是通过errorAttributes.getErrorAttributes得到。容器中DefaultErrorAttributes.getErrorAttributes();默认进行数据处理的。

    自定义ErrorAttributes:

    @Component //给容器中加入我们自定义ErrorAttributes public class MyErrorAttributes extends DefaultErrorAttributes { //返回的map就是页面和JSON获取的所有字段 //WebRequest继承了RequestAttributes @Override public Map<String, Object> getErrorAttributes(WebRequest webRequest, ErrorAttributeOptions options) { Map<String,Object> map=super.getErrorAttributes(webRequest, options); //我们异常处理器携带的数据 Map<String,Object> ext= (Map<String, Object>) webRequest.getAttribute("ext",0); map.put("ext",ext); Throwable error=getError(webRequest); if(error!=null) { map.put("exception",error.getClass().getName()); } return map; } }

    最终的效果:响应是自适应的,可以通过定制ErrorAttributes改变需要返回的内容:

    Processed: 0.009, SQL: 9