一、SpringBoot默認錯誤處理
新建SpringBoot項目,pom.xml
<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>
先只創建一個TestController,此處寫個除零異常,請求這個路徑它會報500錯誤
運行項目,請求路徑:渲染了這樣一個頁面,它說沒有匹配到/error
這說明它是有自動配置這些問題的,SpringBoot它默認是會去找/error路徑對應的頁面,如果沒找到纔會渲染這個頁面。那我們就順藤摸瓜,來下圖這個自動配置裏找一下。
先看BasicErrorController 如果請求頭中的Content-Type是text/html
那就創建一個error頁面看看它是否會跳轉去:
再次請求後,確實跳到這個頁面了
再來看一下DefaultErrorViewResolver(默認的錯誤視圖解析):這裏如果模板引擎可以解析這個視圖地址就用模板引擎解析,模板引擎可用的情況下就返回errorViewName指定的視圖地址。模板引擎不可用就去靜態資源文件夾下找errorViewName對應的視圖。而resolveErrorView 可以很明顯看到它是根據狀態碼定製頁面了。
二、實現ErrorController自定義錯誤頁面
新建CustomErrorController 實現ErrorController,在templates文件夾下新建exception文件夾,對應狀態碼定義幾個頁面,爲區分error頁面,我在新建的error頁面中輸入 模板引擎錯誤頁
運行項目發起請求
三、@ControllerAdvice
和@ExceptionHandler實現
新建一個全局異常處理類 GlobalExceptionHandler 這裏的@Controller和@RestController或者@RestControllerAdvice要靈活運用。我這裏要返回一個視圖
@Controller
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(value = Exception.class)
public Object doExceptionHandler(Exception e, HttpServletRequest request){
ModelAndView mav = new ModelAndView();
mav.addObject("message", e);
mav.addObject("url", request.getRequestURL());
mav.setViewName("exception/error");
return mav;
}
}
修改error模板:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>error</title>
</head>
<body>
<h1>模板引擎錯誤頁</h1>
<h2 th:text="${message}"></h2>
<h2 th:text="${url}"></h2>
</body>
</html>
運行項目,再次請求
四、擴展
想一想,如何把這一篇與 上一篇 封裝統一返回數據格式 做個結合?
快動手試試吧