Springboot實(shí)現(xiàn)自定義錯(cuò)誤頁(yè)面的方法(錯(cuò)誤處理機(jī)制)
一般我們?cè)谧鲰?xiàng)目的時(shí)候,錯(cuò)誤機(jī)制是必備的常識(shí),基本每個(gè)項(xiàng)目都會(huì)做錯(cuò)誤處理,不可能項(xiàng)目一報(bào)錯(cuò)直接跳到原始報(bào)錯(cuò)頁(yè)面,本篇博客主要針對(duì)springboot默認(rèn)的處理機(jī)制,以及自定義錯(cuò)誤頁(yè)面處理進(jìn)行講解,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧!
默認(rèn)效果示例
springboot他是有自己默認(rèn)的處理機(jī)制的。在你剛創(chuàng)建一個(gè)springboot項(xiàng)目去訪(fǎng)問(wèn)一個(gè)沒(méi)有的路徑會(huì)發(fā)現(xiàn)他是會(huì)彈出來(lái)這樣的信息。

而我們用postman直接接口訪(fǎng)問(wèn),會(huì)發(fā)現(xiàn)他返回的不再是頁(yè)面。默認(rèn)響應(yīng)一個(gè)json數(shù)據(jù)

這時(shí)候該有人在想,springboot他是如何識(shí)別我們是否是頁(yè)面訪(fǎng)問(wèn)的呢?
效果示例原因
springboot默認(rèn)錯(cuò)誤處理機(jī)制他是根據(jù)Headers當(dāng)中的Accept來(lái)判斷的,這個(gè)參數(shù)無(wú)論是postman訪(fǎng)問(wèn)還是頁(yè)面訪(fǎng)問(wèn)都會(huì)傳入。
頁(yè)面訪(fǎng)問(wèn)的時(shí)候他傳入的是test/html

而postman是這個(gè)
錯(cuò)誤機(jī)制原理
原因我們大概了解了,接下來(lái)通過(guò)翻看源碼我們簡(jiǎn)單的來(lái)理解一下他的原理。
簡(jiǎn)單回顧springboot原理
springboot之所以開(kāi)箱即用,是因?yàn)楹芏嗫蚣芩呀?jīng)幫我們配置好了,他內(nèi)部有很多AutoConfiguration,其中ErrorMvcAutoConfiguration類(lèi)就是錯(cuò)誤機(jī)制配置。
存放于這個(gè)jar包下

springboo 2.4版本當(dāng)中ErrorMvcAutoConfiguration存放于這個(gè)路徑

springboot 1.5版本ErrorMvcAutoConfiguration存放于這個(gè)路徑

當(dāng)然他只是版本之間類(lèi)存放位置發(fā)生一些改動(dòng),但是源碼區(qū)別不是很大。
springboot內(nèi)部使用到配置的地方,都是去容器當(dāng)中取的,容器的作用就是將這些配置實(shí)例化過(guò)程放到了啟動(dòng),我們?cè)谟玫臅r(shí)候直接從容器當(dāng)中取而無(wú)需創(chuàng)建,這也就是圍繞容器開(kāi)發(fā)的原因,在使用springboot的時(shí)候應(yīng)該也都會(huì)發(fā)現(xiàn),我們想要修改springboot的一些默認(rèn)配置都會(huì)想方設(shè)法把他放到容器當(dāng)中,他才會(huì)生效。
在源碼當(dāng)中會(huì)發(fā)現(xiàn)存在大量@ConditionalOnMissingBean,這個(gè)就是假如我們項(xiàng)目當(dāng)中配置了該項(xiàng)配置,springboot就不會(huì)使用他的默認(rèn)配置了,就直接用我們配置好的。
ErrorMvcAutoConfiguration配置
ErrorMvcAutoConfiguration給容器中添加了以下組件:
1、DefaultErrorAttributes

頁(yè)面當(dāng)中錯(cuò)誤信息,以及訪(fǎng)問(wèn)時(shí)間等等,都是在DefaultErrorAttributes當(dāng)中的這兩個(gè)方法當(dāng)中獲取的。
@Override
public Map<String, Object> getErrorAttributes(WebRequest webRequest, ErrorAttributeOptions options) {
Map<String, Object> 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<String, Object> getErrorAttributes(WebRequest webRequest, boolean includeStackTrace) {
Map<String, Object> errorAttributes = new LinkedHashMap<>();
errorAttributes.put("timestamp", new Date());
addStatus(errorAttributes, webRequest);
addErrorDetails(errorAttributes, webRequest, includeStackTrace);
addPath(errorAttributes, webRequest);
return errorAttributes;
}
2、BasicErrorController
處理默認(rèn)/error請(qǐng)求

也正是BasicErrorController這兩個(gè)方法,來(lái)判斷是返回錯(cuò)誤頁(yè)面還是返回json數(shù)據(jù)
@RequestMapping(produces = MediaType.TEXT_HTML_VALUE)
public ModelAndView errorHtml(HttpServletRequest request, HttpServletResponse response) {
HttpStatus status = getStatus(request);
Map<String, Object> 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<Map<String, Object>> error(HttpServletRequest request) {
HttpStatus status = getStatus(request);
if (status == HttpStatus.NO_CONTENT) {
return new ResponseEntity<>(status);
}
Map<String, Object> body = getErrorAttributes(request, getErrorAttributeOptions(request, MediaType.ALL));
return new ResponseEntity<>(body, status);
}
3、ErrorPageCustomizer

系統(tǒng)出現(xiàn)錯(cuò)誤以后來(lái)到error請(qǐng)求進(jìn)行處理;(就相當(dāng)于是web.xml注冊(cè)的錯(cuò)誤頁(yè) 面規(guī)則)

加粗樣式
4、DefaultErrorViewResolver
DefaultErrorViewResolverConfiguration內(nèi)部類(lèi)
在這里我們可以看出他將DefaultErrorViewResolver注入到了容器當(dāng)中

DefaultErrorViewResolver這個(gè)對(duì)象當(dāng)中有兩個(gè)方法,來(lái)完成了根據(jù)狀態(tài)跳轉(zhuǎn)頁(yè)面。
@Override
public ModelAndView resolveErrorView(HttpServletRequest request, HttpStatus status,
Map<String, Object> model) {
//獲取錯(cuò)誤狀態(tài)碼,這里可以看出他將狀態(tài)碼傳入了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<String, Object> model) {
//從這里可以得知,當(dāng)我們報(bào)404錯(cuò)誤的時(shí)候,他會(huì)去error文件夾找404的頁(yè)面,如果500就找500的頁(yè)面。
String errorViewName = "error/" + viewName;
//模板引擎可以解析這個(gè)頁(yè)面地址就用模板引擎解析
TemplateAvailabilityProvider provider = this.templateAvailabilityProviders
.getProvider(errorViewName, this.applicationContext);
//模板引擎可用的情況下返回到errorViewName指定的視圖地址
if (provider != null) {
return new ModelAndView(errorViewName, model);
}
//模板引擎不可用,就在靜態(tài)資源文件夾下找errorViewName對(duì)應(yīng)的頁(yè)面 error/404.html
return resolveResource(errorViewName, model);
}
組件執(zhí)行步驟
一但系統(tǒng)出現(xiàn)4xx或者5xx之類(lèi)的錯(cuò)誤;ErrorPageCustomizer就會(huì)生效(定制錯(cuò)誤的響應(yīng)規(guī)則);就會(huì)來(lái)到/error 請(qǐng)求;就會(huì)被BasicErrorController處理;去哪個(gè)頁(yè)面是由DefaultErrorViewResolver解析得到的;
代碼示例
這里我選擇直接上代碼,方便大家更快的上手。
1、導(dǎo)入依賴(lài)
這里我引用了thymeleaf模板,springboot內(nèi)部為我們配置好了頁(yè)面跳轉(zhuǎn)功能。
這是本人寫(xiě)的一篇關(guān)于thymeleaf的博客,沒(méi)用過(guò)的或者不是很了解的可以學(xué)習(xí)一下!
thymeleaf學(xué)習(xí): https://blog.csdn.net/weixin_43888891/article/details/111350061.
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> <scope>provided</scope> </dependency> </dependencies>
2、自定義異常
作用:面對(duì)一些因?yàn)闆](méi)找到數(shù)據(jù)而報(bào)空指針的錯(cuò)誤,我們可以采取手動(dòng)拋異常。
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);
//假如是自定義的異常,就讓他進(jìn)入404,其他的一概都進(jìn)入error頁(yè)面
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、創(chuàng)建測(cè)試接口
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 {
//這個(gè)請(qǐng)求我們拋出我們定義的錯(cuò)誤,然后被攔截到直接跳到404,這個(gè)一般當(dāng)有一些數(shù)據(jù)查不到的時(shí)候手動(dòng)拋出
@GetMapping("/test")
public String test(Model model){
String a = null;
if(a == null) {
throw new NotFoundException();
}
System.out.println(a.toString());
return "success";
}
//這個(gè)請(qǐng)求由于a為null直接進(jìn)500頁(yè)面
@GetMapping("/test2")
public String test2(Model model){
String a = null;
System.out.println(a.toString());
return "success";
}
}
5、創(chuàng)建404頁(yè)面
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <h2>404</h2> <p>對(duì)不起,你訪(fǎng)問(wèn)的資源不存在</p> </body> </html>
6、創(chuàng)建error頁(yè)面
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h2>錯(cuò)誤</h2>
<p>對(duì)不起,服務(wù)異常,請(qǐng)聯(lián)系管理員</p>
<!--這段代碼在頁(yè)面不會(huì)展現(xiàn),只會(huì)出現(xiàn)在控制臺(tái),假如線(xiàn)上報(bào)錯(cuò)可以看控制臺(tái)快速鎖定錯(cuò)誤原因-->
<div>
<div th:utext="'<!--'" th:remove="tag"></div>
<div th:utext="'Failed Request URL : ' + ${url}" th:remove="tag"></div>
<div th:utext="'Exception message : ' + ${exception.message}" th:remove="tag"></div>
<ul th:remove="tag">
<li th:each="st : ${exception.stackTrace}" th:remove="tag"><span th:utext="${st}" th:remove="tag"></span></li>
</ul>
<div th:utext="'-->'" th:remove="tag"></div>
</div>
</body>
</html>
7、項(xiàng)目結(jié)構(gòu)
8、運(yùn)行效果
http://localhost:8080/test2
這時(shí)候可以觀(guān)察到,那段代碼在此處生效了,這樣做的好處就是客戶(hù)看不到,看到了反而也不美觀(guān),所以采取這種方式。

訪(fǎng)問(wèn)一個(gè)不存在的頁(yè)面

訪(fǎng)問(wèn)http://localhost:8080/test
這個(gè)時(shí)候會(huì)發(fā)現(xiàn)他跳到了404頁(yè)面

到此這篇關(guān)于Springboot實(shí)現(xiàn)自定義錯(cuò)誤頁(yè)面的方法(錯(cuò)誤處理機(jī)制)的文章就介紹到這了,更多相關(guān)Springboot自定義錯(cuò)誤頁(yè)面內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
http basic authentication通過(guò)post方式訪(fǎng)問(wèn)api示例分享 basic認(rèn)證示例
在HTTP中,基本認(rèn)證是一種用來(lái)允許Web瀏覽器或其他客戶(hù)端程序在請(qǐng)求時(shí)提供以用戶(hù)名和口令形式的憑證,這篇文章主要介紹了http basic authentication通過(guò)post方式訪(fǎng)問(wèn)api示例,大家參考使用吧2014-01-01
SpringBoot項(xiàng)目設(shè)置斷點(diǎn)debug調(diào)試無(wú)效忽略web.xml問(wèn)題的解決
這篇文章主要介紹了SpringBoot項(xiàng)目設(shè)置斷點(diǎn)debug調(diào)試無(wú)效忽略web.xml問(wèn)題的解決,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-08-08
jenkins 構(gòu)建項(xiàng)目之 pipeline基礎(chǔ)教程
​pipeline ,簡(jiǎn)單來(lái)說(shuō),就是一套運(yùn)行在 jenkins 上的工作流框架。這篇文章主要介紹了jenkins 構(gòu)建項(xiàng)目之 pipeline基礎(chǔ)教程,需要的朋友可以參考下2020-07-07
java爬蟲(chóng)Gecco工具抓取新聞實(shí)例
本篇文章主要介紹了JAVA 爬蟲(chóng)Gecco工具抓取新聞實(shí)例,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下。2016-10-10
Java深入了解數(shù)據(jù)結(jié)構(gòu)之棧與隊(duì)列的詳解
這篇文章主要介紹了Java數(shù)據(jù)結(jié)構(gòu)中的棧與隊(duì)列,在Java的時(shí)候,對(duì)于棧與隊(duì)列的應(yīng)用需要熟練的掌握,這樣才能夠確保Java學(xué)習(xí)時(shí)候能夠有扎實(shí)的基礎(chǔ)能力。本文小編就來(lái)詳細(xì)說(shuō)說(shuō)Java中的棧與隊(duì)列,需要的朋友可以參考一下2022-01-01
基于java file 文件操作operate file of java的應(yīng)用
本篇文章介紹了,基于java file 文件操作operate file of java的應(yīng)用。需要的朋友參考下2013-05-05
IDEA創(chuàng)建SpringBoot項(xiàng)目整合mybatis時(shí)mysql-connector-java報(bào)錯(cuò)異常的詳細(xì)分析
最近工作中發(fā)現(xiàn)了個(gè)錯(cuò)誤,分享給同樣遇到這個(gè)問(wèn)題的朋友,這篇文章主要給大家介紹了關(guān)于IDEA創(chuàng)建SpringBoot項(xiàng)目整合mybatis時(shí)mysql-connector-j報(bào)錯(cuò)異常的詳細(xì)分析,需要的朋友可以參考下2023-02-02

