Springboot实现自定义错误页面的方法(错误处理机制)

这篇文章主要介绍了Springboot实现自定义错误页面的方法(错误处理机制),本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

一般我们在做项目的时候,错误机制是必备的常识,基本每个项目都会做错误处理,不可能项目一报错直接跳到原始报错页面,本篇博客主要针对springboot默认的处理机制,以及自定义错误页面处理进行讲解,需要的朋友们下面随着小编来一起学习学习吧!

默认效果示例

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

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

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

效果示例原因

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

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

而postman是这个

 

错误机制原理

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

简单回顾springboot原理

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

存放于这个jar包下

在这里插入图片描述

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

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

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

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

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

ErrorMvcAutoConfiguration配置

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

1、DefaultErrorAttributes

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

 @Override public Map getErrorAttributes(WebRequest webRequest, ErrorAttributeOptions options) { 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 getErrorAttributes(WebRequest webRequest, boolean includeStackTrace) { Map errorAttributes = new LinkedHashMap<>(); errorAttributes.put("timestamp", new Date()); addStatus(errorAttributes, webRequest); addErrorDetails(errorAttributes, webRequest, includeStackTrace); addPath(errorAttributes, webRequest); return errorAttributes; }

2、BasicErrorController

处理默认/error请求

也正是BasicErrorController这两个方法,来判断是返回错误页面还是返回json数据

 @RequestMapping(produces = MediaType.TEXT_HTML_VALUE) public ModelAndView errorHtml(HttpServletRequest request, HttpServletResponse response) { HttpStatus status = getStatus(request); Map model = Collections .unmodifiableMap(getErrorAttributes(request, getErrorAttributeOptions(request, MediaType.TEXT_HTML))); response.setStatus(status.value()); ModelAndView modelAndView = resolveErrorView(request, response, status, model); return (modelAndView != null) ? modelAndView : new ModelAndView("error", model); } @RequestMapping public ResponseEntity> error(HttpServletRequest request) { HttpStatus status = getStatus(request); if (status == HttpStatus.NO_CONTENT) { return new ResponseEntity<>(status); } Map body = getErrorAttributes(request, getErrorAttributeOptions(request, MediaType.ALL)); return new ResponseEntity<>(body, status); }

3、ErrorPageCustomizer

系统出现错误以后来到error请求进行处理;(就相当于是web.xml注册的错误页 面规则)

加粗样式

4、DefaultErrorViewResolver

DefaultErrorViewResolverConfiguration内部类

在这里我们可以看出他将DefaultErrorViewResolver注入到了容器当中

DefaultErrorViewResolver这个对象当中有两个方法,来完成了根据状态跳转页面。

 @Override public ModelAndView resolveErrorView(HttpServletRequest request, HttpStatus status, Map model) { //获取错误状态码,这里可以看出他将状态码传入了resolve方法 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 model) { //从这里可以得知,当我们报404错误的时候,他会去error文件夹找404的页面,如果500就找500的页面。 String errorViewName = "error/" + viewName; //模板引擎可以解析这个页面地址就用模板引擎解析 TemplateAvailabilityProvider provider = this.templateAvailabilityProviders .getProvider(errorViewName, this.applicationContext); //模板引擎可用的情况下返回到errorViewName指定的视图地址 if (provider != null) { return new ModelAndView(errorViewName, model); } //模板引擎不可用,就在静态资源文件夹下找errorViewName对应的页面 error/404.html return resolveResource(errorViewName, model); }

组件执行步骤

一但系统出现4xx或者5xx之类的错误;ErrorPageCustomizer就会生效(定制错误的响应规则);就会来到/error 请求;就会被BasicErrorController处理;去哪个页面是由DefaultErrorViewResolver解析得到的;

代码示例

这里我选择直接上代码,方便大家更快的上手。

1、导入依赖

这里我引用了thymeleaf模板,springboot内部为我们配置好了页面跳转功能。

这是本人写的一篇关于thymeleaf的博客,没用过的或者不是很了解的可以学习一下!

thymeleaf学习: https://blog.csdn.net/weixin_43888891/article/details/111350061.

   org.springframework.bootspring-boot-starter-thymeleaf org.springframework.bootspring-boot-starter-web org.springframework.bootspring-boot-starter-tomcatprovided

2、自定义异常

作用:面对一些因为没找到数据而报空指针的错误,我们可以采取手动抛异常。

 package com.gzl.cn; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; @ResponseStatus(HttpStatus.NOT_FOUND) public class NotFoundException extends RuntimeException { public NotFoundException() { } public NotFoundException(String message) { super(message); } public NotFoundException(String message, Throwable cause) { super(message, cause); } }

3、定义异常拦截

 package com.gzl.cn.handler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.core.annotation.AnnotationUtils; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; @ControllerAdvice public class ControllerExceptionHandler { private final Logger logger = LoggerFactory.getLogger(this.getClass()); @ExceptionHandler(Exception.class) public ModelAndView exceptionHander(HttpServletRequest request, Exception e) throws Exception { logger.error("Requst URL : {},Exception : {}", request.getRequestURL(),e); //假如是自定义的异常,就让他进入404,其他的一概都进入error页面 if (AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class) != null) { throw e; } ModelAndView mv = new ModelAndView(); mv.addObject("url",request.getRequestURL()); mv.addObject("exception", e); mv.setViewName("error/error"); return mv; } }

4、创建测试接口

 package com.gzl.cn.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import com.gzl.cn.NotFoundException; @Controller public class HelloController { //这个请求我们抛出我们定义的错误,然后被拦截到直接跳到404,这个一般当有一些数据查不到的时候手动抛出 @GetMapping("/test") public String test(Model model){ String a = null; if(a == null) { throw new NotFoundException(); } System.out.println(a.toString()); return "success"; } //这个请求由于a为null直接进500页面 @GetMapping("/test2") public String test2(Model model){ String a = null; System.out.println(a.toString()); return "success"; } }

5、创建404页面

   Insert title here 

404

对不起,你访问的资源不存在

6、创建error页面

   Insert title here 

错误

对不起,服务异常,请联系管理员

7、项目结构

 

8、运行效果

http://localhost:8080/test2

这时候可以观察到,那段代码在此处生效了,这样做的好处就是客户看不到,看到了反而也不美观,所以采取这种方式。

访问一个不存在的页面

访问http://localhost:8080/test
这个时候会发现他跳到了404页面

到此这篇关于Springboot实现自定义错误页面的方法(错误处理机制)的文章就介绍到这了,更多相关Springboot自定义错误页面内容请搜索html中文网以前的文章或继续浏览下面的相关文章希望大家以后多多支持html中文网!

以上就是Springboot实现自定义错误页面的方法(错误处理机制)的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » Java