当前位置: 首页 > news >正文

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

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能获取的所有字段}}
http://www.jsqmd.com/news/1281396/

相关文章:

  • 青岛婚纱摄影哪家好?靠谱商家无隐形消费 - 江湖评测
  • Godot游戏开发入门:从零构建玩家角色控制器与移动系统
  • Java实战干货分享
  • AI如何提升学术写作效率:智能文献综述与论文生成
  • 想找永年左旋螺纹锚杆公司?哪家才是合适之选? - 信息热点
  • 5分钟掌握OBS多平台直播推流:obs-multi-rtmp插件完整配置指南
  • 西宁黄金回收市场实测:6家正规门店网格化布局,知语、清月领衔便民服务 - 黄金珠宝
  • AI芯片战争进入“存算一体”终局阶段(英伟达/寒武纪/壁仞技术代差全对比):2025算力采购决策红宝书
  • 2026.7月思茅区防水补漏指南:科学修缮告别年年修年年漏 - 超人防水
  • 短剧男主返乡卖菜:AI短剧占95%,横店的13万群演正在等一个电话
  • “让一堆冰冷的模型‘活‘过来“——揭秘 Unity 的动画系统
  • 中山东区本地防水补漏精选 TOP5 推荐:正规漏水检测维修公司上门师傅推荐:厕所 / 棚顶 / 屋面 / 飘窗 / 阳台 / 地下室 / 厨房渗漏水精准测漏维修(2026 最新) - 超人防水
  • 2026重庆武汉苏州人物铜雕生产大型铜雕定制实测 - LYL仔仔
  • Claude Opus 5大模型工程实践:26%成本优化与智能指数61分技术解析
  • JAVA计算机毕设之基于 SpringBoot 的线上心理答疑互助与情绪疏导管理平台 高校心理健康资讯推送与社区交流系统(完整前后端代码+说明文档+LW,调试定制等)
  • Flask零基础--基础篇
  • 【Bug已解决】glm-5-fp8 zcode str object has no attribute items 解决方案
  • 2026数控伺服弯管机生产厂家,全自动/半自动弯管机均可定制 - 栗子测评
  • 宁波包包回收|合扬支持全城上门,闲置名包现场鉴定当场结算 - 好物测评局
  • 快速搭建数据科学环境之mac docker kaggle image环境配置与使用 VSCode+Docker: 打造最舒适的深度学习环境
  • 2026长沙全城黄金回收点位清单,逸程长沙分店地址,雨花开福卖金参考 - 逸程奢侈品回收中心
  • spring设计模式-单例模式
  • 5个ClosedXML实战技巧:轻松玩转.NET Excel自动化
  • TPIC7710EVM评估模块实战指南:硬件解析与GUI软件高效调试
  • 韶关工厂设备打包回收:厂房电缆拆除+中央空调回收+变压器回收一站式处置推荐 - 广东再生资源回收
  • C 排序算法:快速排序
  • 2026贵阳白云区黄金回收避坑攻略|本地正规门店免费上门,无套路高价收金 - 得天独厚
  • Map 随堂笔记
  • .NET 8配置系统与Serilog日志集成实战指南
  • 2026沈阳和平/沈河/铁西/大东/于洪/浑南/苏家屯/沈北防水堵漏排行榜|屋顶外墙防水、厨卫免砸砖、地下室堵漏、窗台阳台渗水、厂房商铺屋面翻新三家差异化靠谱服务商推荐 - 信息热点