行业资讯
📅 2026/7/28 15:27:54
Spring Boot 定制错误页面/错误数据
1. springboot 默认错误处理浏览器访问返回一个默认的错误页面其他客户端访问默认响应一个json数据springboot中的错误处理自动配置org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfigurationConfigurationConditionalOnWebApplication(typeType.SERVLET)ConditionalOnClass({Servlet.class,DispatcherServlet.class})// Load before the main WebMvcAutoConfiguration so that the error View is availableAutoConfigureBefore(WebMvcAutoConfiguration.class)EnableConfigurationProperties({ServerProperties.class,ResourceProperties.class,WebMvcProperties.class})publicclassErrorMvcAutoConfiguration{BeanConditionalOnMissingBean(valueErrorAttributes.class,searchSearchStrategy.CURRENT)publicDefaultErrorAttributeserrorAttributes(){returnnewDefaultErrorAttributes(this.serverProperties.getError().isIncludeException());}//处理错误请求没有配置的时候默认处理/error请求BeanConditionalOnMissingBean(valueErrorController.class,searchSearchStrategy.CURRENT)publicBasicErrorControllerbasicErrorController(ErrorAttributes errorAttributes){returnnewBasicErrorController(errorAttributes,this.serverProperties.getError(),this.errorViewResolvers);}//系统出现错误以后来到error请求进行处理web.xml注册错误页面//注册错误页面响应规则BeanpublicErrorPageCustomizererrorPageCustomizer(){returnnewErrorPageCustomizer(this.serverProperties,this.dispatcherServletPath);}ConfigurationstaticclassDefaultErrorViewResolverConfiguration{privatefinalApplicationContext applicationContext;privatefinalResourceProperties resourceProperties;DefaultErrorViewResolverConfiguration(ApplicationContext applicationContext,ResourceProperties resourceProperties){this.applicationContextapplicationContext;this.resourcePropertiesresourceProperties;}BeanConditionalOnBean(DispatcherServlet.class)ConditionalOnMissingBeanpublicDefaultErrorViewResolverconventionErrorViewResolver(){returnnewDefaultErrorViewResolver(this.applicationContext,this.resourceProperties);}}privatestaticclassErrorPageCustomizerimplementsErrorPageRegistrar,Ordered{privatefinalServerProperties properties;privatefinalDispatcherServletPath dispatcherServletPath;protectedErrorPageCustomizer(ServerProperties properties,DispatcherServletPath dispatcherServletPath){this.propertiesproperties;this.dispatcherServletPathdispatcherServletPath;}//注册错误页面响应规则OverridepublicvoidregisterErrorPages(ErrorPageRegistry errorPageRegistry){// /errorErrorPage errorPagenewErrorPage(this.dispatcherServletPath.getRelativePath(this.properties.getError().getPath()));errorPageRegistry.addErrorPages(errorPage);}OverridepublicintgetOrder(){return0;}}}//org.springframework.boot.autoconfigure.web.ErrorPropertiespublicclassErrorProperties{/** * Path of the error controller. */Value(${error.path:/error})privateString path/error;...}//org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorControllerControllerRequestMapping(${server.error.path:${error.path:/error}})publicclassBasicErrorControllerextendsAbstractErrorController{...//产生html类型数据处理浏览器请求RequestMapping(producesMediaType.TEXT_HTML_VALUE)publicModelAndViewerrorHtml(HttpServletRequest request,HttpServletResponse response){//状态码HttpStatus statusgetStatus(request);//model数据//getErrorAttributes()调用DefaultErrorAttributes的getErrorAttributes()方法MapString,ObjectmodelCollections.unmodifiableMap(getErrorAttributes(request,isIncludeStackTrace(request,MediaType.TEXT_HTML)));response.setStatus(status.value());//取哪个页面作为错误页面包含页面地址和页面内容ModelAndView modelAndViewresolveErrorView(request,response,status,model);return(modelAndView!null)?modelAndView:newModelAndView(error,model);}//产生json类型数据处理其他客户端请求RequestMappingpublicResponseEntityMapString,Objecterror(HttpServletRequest request){MapString,ObjectbodygetErrorAttributes(request,isIncludeStackTrace(request,MediaType.ALL));HttpStatus statusgetStatus(request);returnnewResponseEntity(body,status);}}//org.springframework.boot.autoconfigure.web.servlet.error.AbstractErrorController#resolveErrorView//所有的ErrorViewResolver 得到ModelAndViewprotectedModelAndViewresolveErrorView(HttpServletRequest request,HttpServletResponse response,HttpStatus status,MapString,Objectmodel){for(ErrorViewResolver resolver:this.errorViewResolvers){ModelAndView modelAndViewresolver.resolveErrorView(request,status,model);if(modelAndView!null){returnmodelAndView;}}returnnull;}publicclassDefaultErrorViewResolverimplementsErrorViewResolver,Ordered{privatestaticfinalMapSeries,StringSERIES_VIEWS;static{MapSeries,StringviewsnewEnumMap(Series.class);views.put(Series.CLIENT_ERROR,4xx);views.put(Series.SERVER_ERROR,5xx);SERIES_VIEWSCollections.unmodifiableMap(views);}...//OverridepublicModelAndViewresolveErrorView(HttpServletRequest request,HttpStatus status,MapString,Objectmodel){ModelAndView modelAndViewresolve(String.valueOf(status.value()),model);if(modelAndViewnullSERIES_VIEWS.containsKey(status.series())){modelAndViewresolve(SERIES_VIEWS.get(status.series()),model);}returnmodelAndView;}privateModelAndViewresolve(String viewName,MapString,Objectmodel){//默认找到一个页面 error/404String errorViewNameerror/viewName;//如果模板引擎可以解析这个页面地址就用模板引擎解析TemplateAvailabilityProvider providerthis.templateAvailabilityProviders.getProvider(errorViewName,this.applicationContext);if(provider!null){//如果模板引擎可用返回errorViewName指定的视图地址returnnewModelAndView(errorViewName,model);}returnresolveResource(errorViewName,model);}privateModelAndViewresolveResource(String viewName,MapString,Objectmodel){//否则在静态资源文件夹下找errorViewName对应的htmlerror/404.htmlfor(String location:this.resourceProperties.getStaticLocations()){try{Resource resourcethis.applicationContext.getResource(location);resourceresource.createRelative(viewName.html);if(resource.exists()){returnnewModelAndView(newHtmlResourceView(resource),model);}}catch(Exceptionex){}}//没找到返回nullreturnnull;}}publicclassDefaultErrorAttributesimplementsErrorAttributes,HandlerExceptionResolver,Ordered{...//BasicErrorController#ModelAndView errorHtml()方法中调用的getErrorAttributes()向错误处理的Model中添加数据publicMapString,ObjectgetErrorAttributes(WebRequest webRequest,booleanincludeStackTrace){MapString,ObjecterrorAttributesnewLinkedHashMap();errorAttributes.put(timestamp,newDate());//时间戳this.addStatus(errorAttributes,webRequest);//状态码this.addErrorDetails(errorAttributes,webRequest,includeStackTrace);this.addPath(errorAttributes,webRequest);returnerrorAttributes;}// timestamp:时间戳// status:状态码// error:错误提示// exception:异常对象// message:异常信息// errors: JSR303数据校验的错误// trace:// path:...}一旦系统出现4xx或者5xx等等错误ErrorPageCustomer定制错误的响应规则就会生效就会到/error请求就会被BasicErrorController处理响应页面是由 **DefaultErrorViewResolver ** 解析得到的如何定制错误处理页面有模板引擎情况下error/状态码将错误页面命名为错误状态码.html放在模板引擎文件夹里面的error文件夹下发生此状态码的错误就会来到对应的页面error/404.html也可以用error4xx.html匹配所有4xx的错误状态码在没有模板引擎的情况下模板引擎找不到error页面会在静态资源文件夹下找以上都没有的时候错误页面会到springboot默认错误提示页面原理可以参照ErrorMvcAutoConfiguration 错误处理的自动配置给容器中添加了以下组件DefaultErrorAttributes帮我们在页面控制信息代码在上面如何定制错误处理json数据Springmvc中可以使用ControllerAdvice和ExceptionHandler({MyException.class})来处理请求异常。这种方法不能自适应 返回页面和数据 的不同情况要自适应可以转发到springboot的/error处理ExceptionHandler({MyException.class})publicStringhandleMyException(Exception e){MapString,ObjectmapnewHashMapString,Objcet();map.put(code,user.notexist);map.put(message,e.getMessage());returnforward:/error;//}这种方法可以自适应但还是来到了错误空白页面错误视图没有解析到因为返回的status状态码200要进入错误处理页面我们需要传入自己的错误状态码org.springframework.boot.autoconfigure.web.servlet.error.AbstractErrorController#getStatus()方法可以看到是request域中的一个属性javax.servlet.error.status_codeExceptionHandler({MyException.class})publicStringhandleMyException(Exception e HttpServletRequest request){MapString,ObjectmapnewHashMapString,Objcet();map.put(code,user.notexist);map.put(message,e.getMessage());request.setAttribute(ext,map);//用于在后面自定义返回数据中取出返回给页面和jsonrequest.setAttribute(javax.servlet.error.status_code,400);returnforward:/error;//}如果要将我们的定制数据携带出去在出现错误后会来到/error请求会被BasicErrorController处理响应出去可以获取的数据由org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController#errorHtml()方法中的getErrorAttributes()也就是org.springframework.boot.autoconfigure.web.servlet.error.AbstractErrorController#getErrorAttributes()方法得到。因为BeanConditionalOnMissingBean(valueErrorController.class,searchSearchStrategy.CURRENT)publicBasicErrorControllerbasicErrorController(ErrorAttributes errorAttributes){returnnewBasicErrorController(errorAttributes,this.serverProperties.getError(),this.errorViewResolvers);}第一种方法 我们可以自定义一个ErrorController实现类或者org.springframework.boot.autoconfigure.web.servlet.error.AbstractErrorController的子类放在容器中。而又因为org.springframework.boot.autoconfigure.web.servlet.error.AbstractErrorController#getErrorAttributes()是在调用org.springframework.boot.web.servlet.error.DefaultErrorAttributes#getErrorAttributes()方法因为BeanConditionalOnMissingBean(valueErrorAttributes.class,searchSearchStrategy.CURRENT)publicDefaultErrorAttributeserrorAttributes(){returnnewDefaultErrorAttributes(this.serverProperties.getError().isIncludeException());}所以我们可以自定义ErrorAttributes的实现类或者继承DefaultErrorAttributes添加自己定义的属性返回给页面ComponentpublicextendsDefaultErrorAttributes{OverridepublicMapString,ObjectgetErrorAttributes(WebRequest webRequest,booleanincludeStackTrace){MapString,ObjecterrorAttributessuper.getErrorAttributes(webRequest,includeStackTrace);errorAttributes.put(name,wangteng);returnerrorAttributes;//页面和json能获取的所有字段}}如果要返回在异常处理中添加的信息可以将数据先放在request中ComponentpublicextendsDefaultErrorAttributes{OverridepublicMapString,ObjectgetErrorAttributes(WebRequest webRequest,booleanincludeStackTrace){MapString,ObjecterrorAttributessuper.getErrorAttributes(webRequest,includeStackTrace);errorAttributes.put(name,wangteng);MapString,Objectext(MapString,Object)webRequest.getAttribute(ext,0);//异常处理器携带数据errorAttributes.put(ext,ext);returnerrorAttributes;//页面和json能获取的所有字段}}