SpringBoot中的全域性異常處理
阿新 • • 發佈:2020-10-31
[toc]
## 本篇要點
- 介紹SpringBoot預設的異常處理機制。
- 如何定義錯誤頁面。
- 如何自定義異常資料。
- 如何自定義檢視解析。
- 介紹@ControllerAdvice註解處理異常。
## 一、SpringBoot預設的異常處理機制
預設情況下,SpringBoot為以下兩種情況提供了不同的響應方式:
1. Browser Clients瀏覽器客戶端:通常情況下請求頭中的Accept會包含text/html,如果未定義/error的請求處理,就會出現如下html頁面:Whitelabel Error Page,關於error頁面的定製,接下來會詳細介紹。
![](https://img2020.cnblogs.com/blog/1771072/202010/1771072-20201031164325800-1870436828.png)
2. Machine Clients機器客戶端:Ajax請求,返回ResponseEntity實體json字串資訊。
```json
{
"timestamp": "2020-10-30T15:01:17.353+00:00",
"status": 500,
"error": "Internal Server Error",
"trace": "java.lang.ArithmeticException: / by zero...",
"message": "/ by zero",
"path": "/"
}
```
SpringBoot預設提供了程式出錯的結果對映路徑/error,這個請求的處理邏輯在BasicErrorController中處理,處理邏輯如下:
```java
// 判斷mediaType型別是否為text/html
@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 modelAndView = resolveErrorView(request, response, status, model);
return (modelAndView != null) ? modelAndView : new ModelAndView("error", model);
}
@RequestMapping
public ResponseEntity