尧图网站建设 尧图网络
  • 首页
  • 关于我们
  • 服务项目
  • 案例展示
  • 建站流程
  • 资讯中心
  • 联系我们
首页/资讯中心/详情

Spring Boot 定制错误页面/错误数据

Spring Boot 定制错误页面/错误数据
📅 发布时间:2026/7/28 15:33:45
1. springboot 默认错误处理

浏览器访问,返回一个默认的错误页面

其他客户端访问,默认响应一个json数据

springboot中的错误处理自动配置:

org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration@Configuration@ConditionalOnWebApplication(type=Type.SERVLET)@ConditionalOnClass({Servlet.class,DispatcherServlet.class})// Load before the main WebMvcAutoConfiguration so that the error View is available@AutoConfigureBefore(WebMvcAutoConfiguration.class)@EnableConfigurationProperties({ServerProperties.class,ResourceProperties.class,WebMvcProperties.class})publicclassErrorMvcAutoConfiguration{@Bean@ConditionalOnMissingBean(value=ErrorAttributes.class,search=SearchStrategy.CURRENT)publicDefaultErrorAttributeserrorAttributes(){returnnewDefaultErrorAttributes(this.serverProperties.getError().isIncludeException());}//处理错误请求,没有配置的时候默认处理/error请求@Bean@ConditionalOnMissingBean(value=ErrorController.class,search=SearchStrategy.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.applicationContext=applicationContext;this.resourceProperties=resourceProperties;}@Bean@ConditionalOnBean(DispatcherServlet.class)@ConditionalOnMissingBeanpublicDefaultErrorViewResolverconventionErrorViewResolver(){returnnewDefaultErrorViewResolver(this.applicationContext,this.resourceProperties);}}privatestaticclassErrorPageCustomizerimplementsErrorPageRegistrar,Ordered{privatefinalServerProperties properties;privatefinalDispatcherServletPath dispatcherServletPath;protectedErrorPageCustomizer(ServerProperties properties,DispatcherServletPath dispatcherServletPath){this.properties=properties;this.dispatcherServletPath=dispatcherServletPath;}//注册错误页面响应规则@OverridepublicvoidregisterErrorPages(ErrorPageRegistry errorPageRegistry){// /errorErrorPage errorPage=newErrorPage(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.BasicErrorController@Controller@RequestMapping("${server.error.path:${error.path:/error}}")publicclassBasicErrorControllerextendsAbstractErrorController{...//产生html类型数据,处理浏览器请求@RequestMapping(produces=MediaType.TEXT_HTML_VALUE)publicModelAndViewerrorHtml(HttpServletRequest request,HttpServletResponse response){//状态码HttpStatus status=getStatus(request);//model数据//getErrorAttributes()调用DefaultErrorAttributes的getErrorAttributes()方法Map<String,Object>model=Collections.unmodifiableMap(getErrorAttributes(request,isIncludeStackTrace(request,MediaType.TEXT_HTML)));response.setStatus(status.value());//取哪个页面作为错误页面,包含页面地址和页面内容ModelAndView modelAndView=resolveErrorView(request,response,status,model);return(modelAndView!=null)?modelAndView:newModelAndView("error",model);}//产生json类型数据,处理其他客户端请求@RequestMappingpublicResponseEntity<Map<String,Object>>error(HttpServletRequest request){Map<String,Object>body=getErrorAttributes(request,isIncludeStackTrace(request,MediaType.ALL));HttpStatus status=getStatus(request);returnnewResponseEntity<>(body,status);}}
//org.springframework.boot.autoconfigure.web.servlet.error.AbstractErrorController#resolveErrorView//所有的ErrorViewResolver 得到ModelAndViewprotectedModelAndViewresolveErrorView(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){returnmodelAndView;}}returnnull;}
publicclassDefaultErrorViewResolverimplementsErrorViewResolver,Ordered{privatestaticfinalMap<Series,String>SERIES_VIEWS;static{Map<Series,String>views=newEnumMap<>(Series.class);views.put(Series.CLIENT_ERROR,"4xx");views.put(Series.SERVER_ERROR,"5xx");SERIES_VIEWS=Collections.unmodifiableMap(views);}...//@OverridepublicModelAndViewresolveErrorView(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);}returnmodelAndView;}privateModelAndViewresolve(String viewName,Map<String,Object>model){//默认找到一个页面 error/404String errorViewName="error/"+viewName;//如果模板引擎可以解析这个页面地址,就用模板引擎解析TemplateAvailabilityProvider provider=this.templateAvailabilityProviders.getProvider(errorViewName,this.applicationContext);if(provider!=null){//如果模板引擎可用,返回errorViewName指定的视图地址returnnewModelAndView(errorViewName,model);}returnresolveResource(errorViewName,model);}privateModelAndViewresolveResource(String viewName,Map<String,Object>model){//否则在静态资源文件夹下找errorViewName对应的html,error/404.htmlfor(String location:this.resourceProperties.getStaticLocations()){try{Resource resource=this.applicationContext.getResource(location);resource=resource.createRelative(viewName+".html");if(resource.exists()){returnnewModelAndView(newHtmlResourceView(resource),model);}}catch(Exceptionex){}}//没找到返回nullreturnnull;}}
publicclassDefaultErrorAttributesimplementsErrorAttributes,HandlerExceptionResolver,Ordered{...//BasicErrorController#ModelAndView errorHtml()方法中调用的getErrorAttributes(),向错误处理的Model中添加数据publicMap<String,Object>getErrorAttributes(WebRequest webRequest,booleanincludeStackTrace){Map<String,Object>errorAttributes=newLinkedHashMap();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){Map<String,Object>map=newHashMap<String,Objcet>();map.put("code","user.notexist");map.put("message",e.getMessage());return"forward:/error";//}

这种方法可以自适应,但还是来到了错误空白页面,错误视图没有解析到,因为返回的status状态码=200,要进入错误处理页面,我们需要传入自己的错误状态码org.springframework.boot.autoconfigure.web.servlet.error.AbstractErrorController#getStatus()方法可以看到是request域中的一个属性"javax.servlet.error.status_code"

@ExceptionHandler({MyException.class})publicStringhandleMyException(Exception e, HttpServletRequest request){Map<String,Object>map=newHashMap<String,Objcet>();map.put("code","user.notexist");map.put("message",e.getMessage());request.setAttribute("ext",map);//用于在后面自定义返回数据中取出,返回给页面和jsonrequest.setAttribute("javax.servlet.error.status_code",400);return"forward:/error";//}

如果要将我们的定制数据携带出去:
在出现错误后,会来到/error请求,会被BasicErrorController处理,响应出去可以获取的数据由org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController#errorHtml()方法中的getErrorAttributes(),也就是org.springframework.boot.autoconfigure.web.servlet.error.AbstractErrorController#getErrorAttributes()方法得到。
因为

@Bean@ConditionalOnMissingBean(value=ErrorController.class,search=SearchStrategy.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()方法,
因为

@Bean@ConditionalOnMissingBean(value=ErrorAttributes.class,search=SearchStrategy.CURRENT)publicDefaultErrorAttributeserrorAttributes(){returnnewDefaultErrorAttributes(this.serverProperties.getError().isIncludeException());}

所以我们可以自定义ErrorAttributes的实现类,或者继承DefaultErrorAttributes,添加自己定义的属性返回给页面

@ComponentpublicextendsDefaultErrorAttributes{@OverridepublicMap<String,Object>getErrorAttributes(WebRequest webRequest,booleanincludeStackTrace){Map<String,Object>errorAttributes=super.getErrorAttributes(webRequest,includeStackTrace);errorAttributes.put("name","wangteng");returnerrorAttributes;//页面和json能获取的所有字段}}

如果要返回在异常处理中添加的信息,可以将数据先放在request中

@ComponentpublicextendsDefaultErrorAttributes{@OverridepublicMap<String,Object>getErrorAttributes(WebRequest webRequest,booleanincludeStackTrace){Map<String,Object>errorAttributes=super.getErrorAttributes(webRequest,includeStackTrace);errorAttributes.put("name","wangteng");Map<String,Object>ext=(Map<String,Object>)webRequest.getAttribute("ext",0);//异常处理器携带数据errorAttributes.put("ext",ext);returnerrorAttributes;//页面和json能获取的所有字段}}

相关新闻

  • Claude Opus 5大模型工程实践:26%成本优化与智能指数61分技术解析
  • 中山东区本地防水补漏精选 TOP5 推荐:正规漏水检测维修公司上门师傅推荐:厕所 / 棚顶 / 屋面 / 飘窗 / 阳台 / 地下室 / 厨房渗漏水精准测漏维修(2026 最新) - 超人防水
  • 【Bug已解决】glm-5-fp8 zcode str object has no attribute items 解决方案

最新新闻

  • Anthropic联手Cognizant 企业AI落地比想象中难
  • 5分钟掌握raylib:零依赖跨平台游戏开发的终极入门指南
  • 为什么92%的AI选手在Phase 2崩溃?——基于2020–2024年17场国际AI赛事数据的失败归因模型
  • 工业电容器故障诊断与预防维护全攻略
  • QQ空间说说备份神器GetQzonehistory:3步永久保存青春记忆
  • 四层板电源层标准化分割实操全流程方案

日新闻

  • 力旷智能:伺服驱动系统在制药收瓶设备中的应用解析
  • 2026 网安入门避坑指南,零基础如何避开无效学习直接上手实战
  • 揭秘CFC项目:如何通过手机摄像头实现850kbps无网络文件传输

周新闻

  • 大连理工大学与东京大学联手打造的“主动型AI助手“
  • 170.2026年国家级科研瓶颈:超精密单点金刚石切削(SPDT)光学表面生成
  • SongBloom:革命性歌曲生成框架深度解析——如何通过交织自回归与扩散模型创作完整音乐

月新闻

  • 2026年6月公司网站搭建最新热门渠道测评:四大低成本/零代码平台对比+避坑
  • 【Linux】Linux arm 编译QT程序,出现expected “}“报错
  • 【MATLAB例程】四基站二维AOA定位与距离辅助增强对比仿真。基于角度观测和测距修正的固定目标平面定位精度分析

关于尧图

  • 公司简介
  • 团队介绍
  • 企业文化
  • 荣誉资质

服务项目

  • 定制开发
  • 电商建站
  • UI 设计
  • 运维服务

快速链接

  • 案例展示
  • 建站流程
  • 常见问题
  • 资讯中心

联系方式

  • 📍北京市朝阳区互联网产业园 A 座 10 层
  • 📞400-888-8888
  • ✉️contact@rkmt.cn
  • 🕐周一至周日 9:00-21:00

© 2024 北京尧图网络科技有限公司 版权所有 | 京 ICP 备 XXXXXXXX 号