怎么在Springboot中自定义错误页面

  

这篇文章给大家介绍怎么在Springboot中自定义错误页面,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。

默认效果示例

springboot他是有自己默认的处理机制的。在你刚创建一个springboot项目去访问一个没有的路径会发现他是会弹出来这样的信息。

怎么在Springboot中自定义错误页面

而我们用postman直接接口访问,会发现他返回的不再是页面。默认响应一个json数据

怎么在Springboot中自定义错误页面

这时候该有人在想,springboot他是如何识别我们是否是页面访问的呢?

效果示例原因

springboot默认错误处理机制他是根据Headers当中的Accept来判断的,这个参数无论是postman访问还是页面访问都会传入。

页面访问的时候他传入的是test/html

怎么在Springboot中自定义错误页面

而postman是这个

怎么在Springboot中自定义错误页面 

错误机制原理

原因我们大概了解了,接下来通过翻看源码我们简单的来理解一下他的原理。

简单回顾springboot原理

springboot之所以开箱即用,是因为很多框架他已经帮我们配置好了,他内部有很多AutoConfiguration,其中ErrorMvcAutoConfiguration类就是错误机制配置。

存放于这个jar包下

怎么在Springboot中自定义错误页面

springboo 2.4版本当中ErrorMvcAutoConfiguration存放于这个路径

怎么在Springboot中自定义错误页面

springboot 1.5版本ErrorMvcAutoConfiguration存放于这个路径

怎么在Springboot中自定义错误页面

当然他只是版本之间类存放位置发生一些改动,但是源码区别不是很大。

springboot内部使用到配置的地方,都是去容器当中取的,容器的作用就是将这些配置实例化过程放到了启动,我们在用的时候直接从容器当中取而无需创建,这也就是围绕容器开发的原因,在使用springboot的时候应该也都会发现,我们想要修改springboot的一些默认配置都会想方设法把他放到容器当中,他才会生效。

在源码当中会发现存在大量@ConditionalOnMissingBean,这个就是假如我们项目当中配置了该项配置,springboot就不会使用他的默认配置了,就直接用我们配置好的。

ErrorMvcAutoConfiguration配置

ErrorMvcAutoConfiguration给容器中添加了以下组件:

1、DefaultErrorAttributes

怎么在Springboot中自定义错误页面

页面当中错误信息,以及访问时间等等,都是在DefaultErrorAttributes当中的这两个方法当中获取的。

 @override
  public  Map<字符串,Object>, getErrorAttributes (WebRequest  webRequest, ErrorAttributeOptions 选项),{
  字符串,Map, errorAttributes =, getErrorAttributes (webRequest, options.isIncluded (Include.STACK_TRACE));
  if  (Boolean.TRUE.equals (this.includeException)), {
  时间=options  options.including (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;
  }
  
  @Override
  @Deprecated
  public  Map<字符串,Object>, getErrorAttributes (WebRequest  webRequest, boolean  includeStackTrace), {
  字符串,Map, errorAttributes =, new  LinkedHashMap<在();
  errorAttributes.put (“timestamp", new 日期());
  addStatus (errorAttributes, webRequest);
  addErrorDetails (errorAttributes, webRequest, includeStackTrace);
  目录(errorAttributes, webRequest);
  return  errorAttributes;
  }

怎么在Springboot中自定义错误页面

Copyright © 2020-2023 feiqueyun.cn. All Rights Reserved. 肥雀云_南京肥雀信息技术有限公司版权所有 南京肥雀信息技术有限公司 苏ICP备16063723号-5