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能获取的所有字段}}

相关新闻

Windows 10也能运行Android应用:WSA-Windows-10逆向移植完整指南

Windows 10也能运行Android应用:WSA-Windows-10逆向移植完整指南

Windows 10也能运行Android应用:WSA-Windows-10逆向移植完整指南 【免费下载链接】WSA-Windows-10 This is a backport of Windows Subsystem for Android to Windows 10. 项目地址: https://gitcode.com/gh_mirrors/ws/WSA-Windows-10 还在为Windows 10无法…

2026/10/24 5:28:10 阅读更多 →
SpringBoot官方推荐缓存框架Caffeine核心原理与实践

SpringBoot官方推荐缓存框架Caffeine核心原理与实践

1. 项目概述:为什么Caffeine成为SpringBoot官方推荐的缓存框架? 在Java应用开发中,缓存是提升系统性能的银弹级解决方案。SpringBoot从2.x版本开始,将Caffeine作为默认缓存推荐替换了曾经的Guava Cache,这背后蕴含着对…

2026/10/24 13:53:36 阅读更多 →
RISC-V IOMMU|第02天:SoC 接口、请求类型与身份模型

RISC-V IOMMU|第02天:SoC 接口、请求类型与身份模型

RISC-V IOMMU|第02天:SoC 接口、请求类型与身份模型今日目标今天聚焦 IOMMU 的外部接口:设备请求如何进入、IOMMU 如何识别设备和进程、不同地址类型如何影响后续路径。后续所有 DDT/PDT/ATS/PRI/MSI 机制都建立在这个入口模型上。读完这篇文…

2026/10/24 7:40:25 阅读更多 →

最新新闻

Electron桌面应用开发实战:从环境搭建到打包发布全流程

Electron桌面应用开发实战:从环境搭建到打包发布全流程

做前端这些年,我大部分时间都在跟浏览器标签页打交道,直到第一次把桌面应用跑起来,才发现原来自己一直被限制在地址栏和刷新按钮围起来的框框里。Electron这个词,最开始是在某段时间频繁出现在同事的讨论里,一个用HTML…

2026/10/28 23:48:14 阅读更多 →
滑盖智能锁T109深度解析:结构原理、安装调试与故障排查

滑盖智能锁T109深度解析:结构原理、安装调试与故障排查

简介:亚太天能T109滑盖智能锁产品说明书是一份PDF格式的官方技术文档,主要面向智能锁安装人员、终端用户及售后维护者,帮助快速掌握产品安装、配置与常见故障处理。全包仅1个PDF文件,大小4.37MB,内容结构清晰&#xff…

2026/10/29 8:45:01 阅读更多 →
PMSM弱磁控制原理与Simulink建模:高速AGV驱动系统设计指南

PMSM弱磁控制原理与Simulink建模:高速AGV驱动系统设计指南

上个月我在调试一台高速AGV的驱动系统,整车要求空载跑到8m/s,电机转速已经拉到额定点,驱动器的输出电压也顶到了母线电压极限附近。再往上踩速度指令,转速纹丝不动,三相电流反而开始震荡。那会儿我的第一反应就是&…

2026/10/29 9:52:56 阅读更多 →
C++核心知识点:从内存管理到STL的实战指南

C++核心知识点:从内存管理到STL的实战指南

C 这门语言我前前后后折腾了十几年,用它写过嵌入式驱动、做过游戏服务端,也搭过基础组件库。每次看到新人一头扎进"C 核心知识点"这个搜索词,我其实挺感慨的——这门语言的难点从来不是语法多,而是知识点之间的耦合太深…

2026/10/28 22:10:30 阅读更多 →
T109滑盖智能锁怎么装?安装调试与故障排查全攻略

T109滑盖智能锁怎么装?安装调试与故障排查全攻略

简介:亚太天能T109滑盖智能锁产品说明书以PDF格式发布,适合智能锁用户、安装人员与售后维修人员阅读。内容围绕T109系列指纹密码刷卡锁展开,先介绍前面板、后面板、锁体、机械钥匙、电池盒盖等部件名称与功能,再给出完整安装步骤&…

2026/10/29 9:51:34 阅读更多 →
LLM知识降熵:从信息垄断到理解权下放

LLM知识降熵:从信息垄断到理解权下放

你有没有过这种经历:翻开源码注释、论文摘要或者一份专业报告,每个字都认识,连在一起却像天书。想找人聊聊,身边要么没人懂,要么懂的懒得跟你解释。后来我试着把同一段内容丢给一个大语言模型,几秒钟之后&a…

2026/10/29 8:44:28 阅读更多 →

日新闻

周新闻

月新闻

我发现了一个新思路:用 Remotion + Claude Code 像写代码一样自动化生成短视频

我发现了一个新思路:用 Remotion + Claude Code 像写代码一样自动化生成短视频

/* MD / 富文本中的 .toc(含博客园搬家等嵌套结构);.toc-box 在侧栏,不受影响 */#content_views .toc,/* 编辑器常在目录前后插入空 p(:empty 仍占 20px),一并去掉避免顶空隙 */#content_views.markdown_views > p:empty:has(+ .toc),#content_views.markdown_views …

2026/10/28 16:58:40 阅读更多 →
Windows下 Codex 中 Chrome 和 Computer Use 插件不可用问题排查及解决参考方式:TaoToken 统一 Key 配置与验证

Windows下 Codex 中 Chrome 和 Computer Use 插件不可用问题排查及解决参考方式:TaoToken 统一 Key 配置与验证

/* MD / 富文本中的 .toc(含博客园搬家等嵌套结构);.toc-box 在侧栏,不受影响 */#content_views .toc,/* 编辑器常在目录前后插入空 p(:empty 仍占 20px),一并去掉避免顶空隙 */#content_views.markdown_views > p:empty:has(+ .toc),#content_views.markdown_views …

2026/10/29 9:42:17 阅读更多 →
黑夜航拍船只数据集训练YOLOV5模型全流程解析

黑夜航拍船只数据集训练YOLOV5模型全流程解析

/* MD / 富文本中的 .toc(含博客园搬家等嵌套结构);.toc-box 在侧栏,不受影响 */#content_views .toc,/* 编辑器常在目录前后插入空 p(:empty 仍占 20px),一并去掉避免顶空隙 */#content_views.markdown_views > p:empty:has(+ .toc),#content_views.markdown_views …

2026/10/28 19:25:09 阅读更多 →