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

网友投稿 400 2023-02-22

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) {

qJbSBCfXrMap 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就会生效(定qJbSBCfXr制错误的响应规则);就会来到/error 请求;就会被BasicErrorController处理;去哪个页面是由DefaultErrorViewResolver解析得到的;

代码示例

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

1、导入依赖

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

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

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

org.springframework.boot

spring-boot-starter-thymeleaf

org.springframework.boot

spring-boot-starter-web

org.springframework.boot

spring-boot-starter-tomcat

provided

2、自定义异常

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

package com.gzl-;

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-.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-.controller;

import org.springframework.stereotype.Controller;

import org.springframework.ui.Model;

import org.springframework.web.bind.annotation.GetMapping;

import com.gzl-.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页面

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

6、创建error页面

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

7、项目结构

8、运行效果

http://localhost:8080/test2

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

访问一个不存在的页面

访问http://localhost:8080/test

这个时候会发现他跳到了404页面

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:springboot日志切面通用类实例详解
下一篇:微信小程序指纹识别api(微信小程序获取指纹)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~