文章目录

  • 1、SpringBoot默认的错误处理机制
  • 2、错误处理原理
    • (1)DefaultErrorAttributes
    • (2)BasicErrorController:处理默认的/error请求
    • (4)DefaultErrorViewResolver:
  • 3、如何定制错误响应
    • 3.1 如何定制错误的页面
    • 3.2 如何定制错误的json数据
  • 4、最终效果

1、SpringBoot默认的错误处理机制

SpringBoot对错误默认的效果,主要分为两种:一种是浏览器,另一种是其他客户端。

(1)浏览器返回一个默认的错误页面

浏览器发送请求的请求头中携带了关键的信息text/html

(2)如果是其他客户端,默认响应一个json数据,以postman为例,具体如下:

postman发送请求的请求头中accept信息如下:

2、错误处理原理

一旦系统出现4xx或者5xx之类的错误,ErrorPageCustomizer就会生效(定制错误的响应规则);就会来到/error请求,就会被BasicErrorController处理

响应页面:去哪个页面是由DefaultErrorViewResolver解析得到的;

protected ModelAndView resolveErrorView(HttpServletRequest request,HttpServletResponse response, HttpStatus status, Map<String, Object> model) {//ErrorViewResolver:异常视图解析器for (ErrorViewResolver resolver : this.errorViewResolvers) {ModelAndView modelAndView = resolver.resolveErrorView(request, status, model);if (modelAndView != null) {return modelAndView;}}return null;}

主要参照错误自动配置类ErrorMvcAutoConfiguration,该错误自动配置类给容器添加了如下组件:DefaultErrorAttributes、BasicErrorController、ErrorPageCustomizer、DefaultErrorViewResolver,每个组件的具体用途如下:

(1)DefaultErrorAttributes

//构造在页面上显示的共享信息
@Overridepublic Map<String, Object> getErrorAttributes(RequestAttributes requestAttributes,boolean includeStackTrace) {Map<String, Object> errorAttributes = new LinkedHashMap<String, Object>();errorAttributes.put("timestamp", new Date());addStatus(errorAttributes, requestAttributes);addErrorDetails(errorAttributes, requestAttributes, includeStackTrace);addPath(errorAttributes, requestAttributes);return errorAttributes;}

(2)BasicErrorController:处理默认的/error请求

@Controller
@RequestMapping("${server.error.path:${error.path:/error}}")
public class BasicErrorController extends AbstractErrorController {private final ErrorProperties errorProperties;//产生的html类型的数据;统一处理浏览器发送的请求@RequestMapping(produces = "text/html")public ModelAndView errorHtml(HttpServletRequest request,HttpServletResponse response) {HttpStatus status = getStatus(request);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 ? new ModelAndView("error", model) : modelAndView);}@RequestMapping@ResponseBody//产生json数据;统一出来来自其他客户端的请求public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {Map<String, Object> body = getErrorAttributes(request,isIncludeStackTrace(request, MediaType.ALL));HttpStatus status = getStatus(request);return new ResponseEntity<Map<String, Object>>(body, status);}

###(3)ErrorPageCustomer:

@Overridepublic void registerErrorPages(ErrorPageRegistry errorPageRegistry) {//注册错误响应规则;当系统发生错误后,去哪个路径,通过getPath()进行配置ErrorPage errorPage = new ErrorPage(this.properties.getServletPrefix()+ this.properties.getError().getPath());errorPageRegistry.addErrorPages(errorPage);}
public class ErrorProperties {/*** 系统出现错误以后来到error请求进行处理(web.xml注册的错误页       *面规划)*/@Value("${error.path:/error}")private String path = "/error";

(4)DefaultErrorViewResolver:

@Overridepublic ModelAndView resolveErrorView(HttpServletRequest request, HttpStatus status,Map<String, Object> model) {ModelAndView modelAndView = resolve(String.valueOf(status), model);if (modelAndView == null && SERIES_VIEWS.containsKey(status.series())) {modelAndView = resolve(SERIES_VIEWS.get(status.series()), model);}return modelAndView;}private ModelAndView resolve(String viewName, Map<String, Object> model) {//默认SpringBoot可以去找到一个页面:error/404String errorViewName = "error/" + viewName;//模板引擎可以解析这个页面地址就用模板引擎解析TemplateAvailabilityProvider provider = this.templateAvailabilityProviders.getProvider(errorViewName, this.applicationContext);if (provider != null) {//模板引擎可用的情况下返回到errorViewName指定的视图地址return new ModelAndView(errorViewName, model);}//模板引擎不可用,就在静态资源文件夹下找到errorViewName对应的页面 error/404.htmlreturn resolveResource(errorViewName, model);}private ModelAndView resolveResource(String viewName, Map<String, Object> model) {for (String location : this.resourceProperties.getStaticLocations()) {try {Resource resource = this.applicationContext.getResource(location);resource = resource.createRelative(viewName + ".html");if (resource.exists()) {return new ModelAndView(new HtmlResourceView(resource), model);}}catch (Exception ex) {}}return null;}

注意:当模板引擎不可用的时候,就会在静态资源文件夹下找对应的错误页面

3、如何定制错误响应

3.1 如何定制错误的页面

(1)有模板引擎的情况下,error/状态码

将错误页面命名为错误状态码.html放在模板引擎文件夹里面的error文件夹下,发生此状态码的错误就会来到对应的页面;

可以使用4xx和5xx作为错误页面的文件名来匹配这种类型的所有错误,精确优先(优先寻找精确的状态码.html)

页面能获取的信息如下:

  • timestamp:时间戳
  • status:状态码
  • error:错误提示
  • exception:异常对象
  • message:异常信息
  • errors:JSR303数据校验的错误都在这里

(2)没有模板引擎(模板引擎找不到这个错误页面),去静态资源文件夹下找

静态资源文件夹的路径有以下四种

(3)以上都没有错误页面,就是默认来到SpringBoot默认的错误提示页面

builder.append("<html><body><h1>Whitelabel Error Page</h1>").append("<p>This application has no explicit mapping for /error, so you are seeing this as a fallback.</p>").append("<div id='created'>").append(timestamp).append("</div>").append("<div>There was an unexpected error (type=").append(htmlEscape(model.get("error"))).append(", status=").append(htmlEscape(model.get("status"))).append(").</div>");if (message != null) {builder.append("<div>").append(htmlEscape(message)).append("</div>");}if (trace != null) {builder.append("<div style='white-space:pre-wrap;'>").append(htmlEscape(trace)).append("</div>");}builder.append("</body></html>");response.getWriter().append(builder.toString());

3.2 如何定制错误的json数据

(1)默认的json数据内容

(2)自定义异常处理&返回定制json数据

@ControllerAdvice
public class MyExceptionHandler {//浏览器和客户端返回的都是json数据@ResponseBody@ExceptionHandler(UserNoExistException.class)public Map<String, Object> handleException(Exception e){Map<String, Object> map = new HashMap<>();map.put("code","user.notexist");map.put("message",e.getMessage());return map;}
}

以上自定义处理方式的缺点是:没有自适应效果,所谓的自适应效果就是:当用浏览器发送请求的时候,返回的应该是html页面;通过其他客户端发送请求的时候,返回的应该是json数据。

(3)转发到/error进行自适应响应效果处理

@ControllerAdvice
public class MyExceptionHandler {@ExceptionHandler(UserNoExistException.class)public String handleException(Exception e, HttpServletRequest request){Map<String, Object> map = new HashMap<>();//传入我们自己的错误状态码4xx、5xx,默认的是200,,否则就不会进入到定制错误页面的解析流程中//参考AbstractErrorController类中的getStatus方法中的代码:Integer statusCode = (Integer) request              .getAttribute("javax.servlet.error.status_code");request.setAttribute("javax.servlet.error.status_code",500);map.put("code","user.notexist");map.put("message",e.getMessage());//将异常信息带到界面上去request.setAttribute("ext",map);//转发到/error        return "forward:/error";}
}

(4)将我们的定制数据携带出来

我们可以自定义异常处理器,在异常处理器中捕获一些重要的反馈信息。当出现错误后,会来到/error请求,会被BasicErrorController处理,响应出去可以获取的数据是由getErrorAttributes得到的(AbstractErrorController(ErrorController)规定的方法);

protected Map<String, Object> getErrorAttributes(HttpServletRequest request,boolean includeStackTrace) {RequestAttributes requestAttributes = new ServletRequestAttributes(request);//构造返回的数据return this.errorAttributes.getErrorAttributes(requestAttributes,includeStackTrace);}

1)完全来编写一个ErrorController的实现类【或者编写AbstractErrorController的子类】,放在容器中;

2)页面上能用的数据,或者是json返回能用的数据都是通过errorAttributes.getErrorAttributes得到;

3)容器中DefaultErrorAttributes.getErrorAttributes();默认进行数据处理的;

自定义ErrorAttributes类

@Component
public class MyErrorAttributes extends DefaultErrorAttributes {//返回值的map就是页面和json能获取的所有字段信息@Overridepublic Map<String, Object> getErrorAttributes(RequestAttributes requestAttributes, boolean includeStackTrace) {Map<String, Object> map = super.getErrorAttributes(requestAttributes, includeStackTrace);//对每个提示信息添加公共的属性信息map.put("company","htzw");//我们自定义的异常处理器携带的数据Map<String, Object> ext = (Map<String, Object>) requestAttributes.getAttribute("ext", 0);map.put("ext",ext);return map;}
}

4、最终效果

最终的效果是:响应式自适应的,可以通过定制ErrorAttributes改变需要返回的内容

浏览器返回信息如下:

客户端返回信息如下:

SpringBoot之错误处理机制相关推荐

  1. springboot返回modelandview 找不到视图_SpringBoot错误处理机制及原理

    SpringBoot错误信息处理机制 ★ 在一个web项目中,总需要对一些错误进行界面或者json数据返回,已实现更好的用户体验,SpringBoot中提供了对于错误处理的自动配置 " Er ...

  2. SpringBoot默认的错误处理机制

    错误处理机制: 访问一个不存在的页面时,或者程序抛出异常时 默认效果 浏览器返回一个错误的页面,注意查看浏览器发送请求的请求头 可以使用专业的软件比如postman分析返回的json数据 spring ...

  3. Springboot 错误处理机制

    SpringBoot默认的错误处理机制 即我们常见的白色的ErrorPage页面 浏览器发送的请求头: 如果是其他的请求方式,比如客户端,则相应一个json数据: 原理:是通过 ErrorMvcAut ...

  4. SpringBoot——错误处理机制 定制错误页面 (源码分析)

    目录 一.错误处理机制 二.ErrorPageCustomizer 三.BasicErrorController 四.DefaultErrorViewResolver 五.如何定制错误响应页面 六.D ...

  5. SpringBoot默认包扫描机制及@ComponentScan指定扫描路径详解

    SpringBoot默认包扫描机制及@ComponentScan指定扫描路径详解 SpringBoot默认包扫描机制 标注了@Component和@Component的衍生注解如@Controller ...

  6. SpringBoot默认包扫描机制及使用@ComponentScan指定扫描路径

    SpringBoot默认包扫描机制 标注了@Component和@Component的衍生注解如@Controller,@Service,@Repository就可以把当前的Bean加入到IOC容器中 ...

  7. Go语言的错误异常处理机制及其应用

    一.背景 在日常编写golang程序或阅读别人的golang代码时,我们总会看到如下的一堆代码块: xx, err = func(xx) if err != nil {//do sth. to tac ...

  8. Vue.js@2.6.10更新内置错误处机制,Fundebug同步支持相应错误监控

    2019独角兽企业重金招聘Python工程师标准>>> 摘要: Fundebug 的 JavaScript 错误监控插件同步支持 Vue.js 异步错误监控. Vue.js 从诞生至 ...

  9. onresize事件会被多次触发_玩转SpringBoot之通过事件机制参与SpringBoot应用的启动过程...

    生命周期和事件监听 一个应用的启动过程和关闭过程是归属到"生命周期"这个概念的范畴. 典型的设计是在启动和关闭过程中会触发一系列的"事件",我们只要监听这些事件 ...

最新文章

  1. android复制链接到粘贴板,Android复制粘贴到剪贴板
  2. python一个函数可以有参数也可以没有参数_python 传入任意多个参数(方法调用可传参或不传参)...
  3. 在VS中建立一个易于管理的C++工程
  4. pcb 理论阻值、 过孔_超实用!PCB设计中过孔常用的6种处理方式
  5. 鸿蒙系统正式开源,余承东:鸿蒙系统正式开源,友商也可以使用!
  6. JSP--(使用请求转发的动作标识jsp:forward)
  7. unity3d 求两个点长度_三年级上册求组合图形周长专项练习,附答案
  8. SQL系列(五)—— 排序(order by)
  9. webpack打包初体验
  10. 如何用手机实现高精度定位导航
  11. EnableViewState
  12. 一周成python大神_2个月把你变成selenium+Python大神,上海悠悠带你飞!
  13. android 小米相机权限,小米如何设置访问相机权限设置
  14. 数据分析报表设计开发要素
  15. 百度地图LV1.5实践项目开发工具类bmap.util.jsV1.3
  16. win10系统关机被阻止解决方法
  17. 全网最全AD16——PCB布线
  18. Java Word中的文本、图片替换功能
  19. Pycharm编译代码时出现“SyntaxError: Non-UTF-8 code starting with ‘\xca‘ in file ...“
  20. 一、万信金融项目——项目介绍

热门文章

  1. IT行业老程序员的经验之谈:爬虫学到什么程度可以找到工作?
  2. java 导出excel 注解_Java基于注解和反射导入导出Excel
  3. android下载后的app自动安装,Android 7.0 下载APK后自动安装
  4. linux给用户写任务计划,linux——计划任务
  5. 实战讲解Python函数参数
  6. 跳过51单片机,直接学STM32有什么严重后果?
  7. 如何学好单片机编程?学好单片机的基础是什么?
  8. java中字节输入流和输出流的简单使用例子
  9. 关于学习Python的一点学习总结(31->继承及多态)
  10. 华北电力大学计算机导论试题,保定华北电力大学计算机与科学大一课程