怎么在Springboot中自定义错误页面
创始人
2024-12-28 06:02:41
0次

默认效果示例

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 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请求

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

也正是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

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

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

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

加粗样式

4、DefaultErrorViewResolver

DefaultErrorViewResolverConfiguration内部类

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

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

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.boot
		spring-boot-starter-thymeleaf
	
	
		org.springframework.boot
		spring-boot-starter-web
	

	
		org.springframework.boot
		spring-boot-starter-tomcat
		provided
	
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、项目结构

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

8、运行效果

http://localhost:8080/test2

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

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

访问一个不存在的页面

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

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

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

相关内容

热门资讯

空调连续工作多久需要停机休息 空调连续工作的时间取决于多个因素,包括空调的型号、功率、使用环境和维护情况等。一般来说,空调可以连续...
空调哪个符号是除湿的 空调除湿功能通常用一个水滴形状的符号表示。不同品牌和型号的空调遥控器可能会有所差异,但一般来说,除湿...
格力空调多长时间加一次氟利昂 1、一般情况下,空调对氟利昂的使用量是非常小的,所以在空调使用了四年左右的时候再考虑加也没问题。2、...
空调用多长时间需要加氟一次 一般情况下是五年。当出现以下这几种情况时,空调才需要加氟。1、空调的室内机和室外机各有两个接口,当接...
格调生活·C标思享荟:卡萨帝在... 9月12日的郑州龙湖金融岛,夜风轻拂,灯光璀璨。“C标时刻共传奇——卡萨帝思享荟暨20周年品牌盛典郑...
品牌价值破千亿、高端份额持续领... 9月12日,“C标时刻共传奇——卡萨帝思享荟暨20周年品牌盛典郑州站”在郑州龙湖金融岛举办。2026...
空调主板坏了修800还是换新的 空调主板坏了是修还是换新,需要考虑多个因素,以下是一些建议:1. 维修成本:如果维修费用较低,比如 ...
空调开多久需要休息多长时间 问题:空调开多久需要休息多长时间回答:1、在使用空调的过程中,一般空调开7~8个小时左右需要休息2~...
中央空调多长时间清洗一次 1、一般空调开机前清洗一次即可,空调开机中间时段再清洗一次,空调关机时清洗一次,这样比较合理。2、空...
中央空调氟利昂多久加一次 看空调制热和制冷程度,很多人的观点认为氟利昂必须一年放一次,其实这个观点是错误的,理解上面有点偏差,...