1、SpringBoot默認的錯誤處理機制
默認效果:1)、瀏覽器,返回一個默認的錯誤頁面
瀏覽器發送請求的請求頭:
2)、如果是其他客戶端,默認響應一個json數據
原理:
默認情況下,Spring Boot提供/error 映射,以合理的方式處理所有錯誤,並在servlet容器中註冊爲“全局”錯誤頁面。對於計算機客戶端,它會生成一個JSON響應,其中包含錯誤,HTTP狀態和異常消息的詳細信息。
對於瀏覽器客戶端,有一個“whitelabel”錯誤視圖,以HTML格式呈現相同的數據(要自定義它,添加一個解析
爲error 的View )。要完全替換默認行爲,您可以實現ErrorController 並註冊該類型的bean定義或添加bean類型ErrorAttributes 以使用現有機制但替換內容。
要完全替換默認行爲,您可以實現ErrorController 並註冊該類型的bean定義或添加bean類型ErrorAttributes 以使用現有機制但替換內容。
BasicErrorController 可以用作自定義ErrorController 的基類。如果要爲新內容類型添加處理程序,則此功能特別有用(默認情況下,專門處理text/html 併爲其他所有內容提供後備)。爲此,請擴展BasicErrorController ,添加具有produces 屬性的@RequestMapping 的公共方法,並創
建新類型的bean。
可以參照ErrorMvcAutoConfiguration;錯誤處理的自動配置;
給容器中添加了以下組件
1、DefaultErrorAttributes:
@Override
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;
}
注意調用順序:
在BasicErrorController:(@RequestMapping(produces = MediaType.TEXT_HTML_VALUE))
Map<String, Object> model = Collections.unmodifiableMap(getErrorAttributes(request, isIncludeStackTrace(request, MediaType.TEXT_HTML)))
點進去到:AbstractErrorController中
protected Map<String, Object> getErrorAttributes(HttpServletRequest request, boolean includeStackTrace) { WebRequest webRequest = new ServletWebRequest(request); return this.errorAttributes.getErrorAttributes(webRequest, includeStackTrace);}
再點進去到ErrorAttributes接口中,觀察實現類,幫我們在頁面共享信息
@Order(Ordered.HIGHEST_PRECEDENCE)public class DefaultErrorAttributes implements ErrorAttributes, HandlerExceptionResolver, Ordered {
@Override
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:
處理默認/error請求
@Controller
@RequestMapping("${server.error.path:${error.path:/error}}")
public class BasicErrorController extends AbstractErrorController {
//產生html類型的數據;瀏覽器發送的請求來到這個方法處理
@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, isIncludeStackTrace(request, MediaType.TEXT_HTML)));
response.setStatus(status.value());
//去哪個頁面作爲錯誤頁面;包含頁面地址和頁面內容
ModelAndView modelAndView = resolveErrorView(request, response, status, model);
return (modelAndView != null) ? modelAndView : new ModelAndView("error", model);
}
//產生json數據,其他客戶端來到這個方法處理;
@RequestMapping
public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
Map<String, Object> body = getErrorAttributes(request, isIncludeStackTrace(request, MediaType.ALL));
HttpStatus status = getStatus(request);
return new ResponseEntity<>(body, status);
}
}
3、ErrorPageCustomizer:
系統出現錯誤以後來到error請求進行處理;(web.xml註冊的錯誤頁面規則)
private static class ErrorPageCustomizer implements ErrorPageRegistrar, Ordered {
private final ServerProperties properties;
private final DispatcherServletPath dispatcherServletPath;
protected ErrorPageCustomizer(ServerProperties properties, DispatcherServletPath dispatcherServletPath) {
this.properties = properties;
this.dispatcherServletPath = dispatcherServletPath;
}
@Override
public void registerErrorPages(ErrorPageRegistry errorPageRegistry) {
//系統出現錯誤來到error請求處理
ErrorPage errorPage = new ErrorPage(
this.dispatcherServletPath.getRelativePath(this.properties.getError().getPath()));
errorPageRegistry.addErrorPages(errorPage);
}
@Override
public int getOrder() {
return 0;
}
}
*/
@Value("${error.path:/error}")
private String path = "/error";
4、DefaultErrorViewResolver:
public class DefaultErrorViewResolver implements ErrorViewResolver, Ordered {
private static final Map<Series, String> SERIES_VIEWS;
static {
Map<Series, String> views = new EnumMap<>(Series.class);
views.put(Series.CLIENT_ERROR, "4xx");
views.put(Series.SERVER_ERROR, "5xx");
SERIES_VIEWS = Collections.unmodifiableMap(views);
}
private ModelAndView resolve(String viewName, Map<String, Object> model) {
//默認SpringBoot可以去找到一個頁面? error/404
String errorViewName = "error/" + viewName;
//如果模板引擎可以解析這個頁面地址就用模板引擎解析
TemplateAvailabilityProvider provider = this.templateAvailabilityProviders.getProvider(errorViewName,
this.applicationContext);
if (provider != null) {
//模板引擎可用的情況下返回到errorViewName指定的視圖地址
return new ModelAndView(errorViewName, model);
}
//模板引擎不可用,就在靜態資源文件夾下找errorViewName對應的頁面 error/404.html
return resolveResource(errorViewName, model);
}
private ModelAndView resolveResource(String viewName, Map<String, Object> model) {
//靜態資源文件夾下 404.html
for (String location : this.resourceProperties.getStaticLocations()) {
try {
Resource resource = this.applicationContext.getResource(location);
resource = resource.createRelative(viewName + ".html");
if (resource.exists()) {
return new ModelAndView(new HtmlResourceView(resource), model);
}
}
catch (Exception ex) {
}
}
return null;
}
}
調用步驟:
一但系統出現4xx或者5xx之類的錯誤;ErrorPageCustomizer就會生效(定製錯誤的響應規則);就會來到/error請求;就會被BasicErrorController處理;
1)響應頁面;去哪個頁面是DefaultErrorViewResolver解析得到的;
protected ModelAndView resolveErrorView(HttpServletRequest request, HttpServletResponse response, HttpStatus status,
Map<String, Object> model) {
//所有的ErrorViewResolver得到ModelAndView
for (ErrorViewResolver resolver : this.errorViewResolvers) {
ModelAndView modelAndView = resolver.resolveErrorView(request, status, model);
if (modelAndView != null) {
return modelAndView;
}
}
return null;
}
2、定製錯誤響應
1)、如何定製錯誤的頁面;
1)、有模板引擎的情況下;error/狀態碼; 【將錯誤頁面命名爲 錯誤狀態碼.html 放在模板引擎文件夾裏面的 error文件夾下】,發生此狀態碼的錯誤就會來到 對應的頁面;
我們可以使用4xx和5xx作爲錯誤頁面的文件名來匹配這種類型的所有錯誤,精確優先(優先尋找精確的狀態碼.html);
頁面能獲取的信息;
timestamp:時間戳
status:狀態碼
error:錯誤提示
exception:異常對象
message:異常消息
errors:JSR303數據校驗的錯誤都在這裏
2)、沒有模板引擎(模板引擎找不到這個錯誤頁面),靜態資源文件夾下找;
3)、以上都沒有錯誤頁面,就是默認來到SpringBoot默認的錯誤提示頁面;
2)、如何定製錯誤的json數據;
還可以定義使用@ControllerAdvice 註釋的類,以自定義要爲特定控制器和/或異常類型返回的JSON數據
1)、自定義異常處理&返回定製json數據;
@ControllerAdvice
public class MyExceptionHandler {
/*
* @Author: jiatp
* Description:返回的是json數據
*/
@ResponseBody
@ExceptionHandler(UserNotExistException.class)
public Map<String,Object> handlerException(Exception e){
Map<String,Object> map = new HashMap<>();
map.put("code","user.notexist");
map.put("message",e.getMessage());
return map;
}
}
缺點:沒有自適應效果…即瀏覽器訪問返回頁面,其他客戶端訪問返回json數據
2)、轉發到/error進行自適應響應效果處理
package com.spboot.springboot04.controller;
import com.spboot.springboot04.exception.UserNotExistException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
/*
* @Author: jiatp
* Description:自定義異常處理器
*/
@ControllerAdvice
public class MyExceptionHandler {
@ExceptionHandler(UserNotExistException.class)
public String handlerException(Exception e, HttpServletRequest request){
Map<String,Object> map = new HashMap<>();
map.put("code","user.notexist");
map.put("message",e.getMessage());
//傳入自己的錯誤狀態碼 4xx,5XX
/*
Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
*/
request.setAttribute("javax.servlet.error.status_code",500);
request.setAttribute("ext",map);
//轉發到/error
return "forward:/error";
}
}
轉發到/error請求由BasicErrorController處理, 傳入自己的錯誤狀態碼 4xx,5XX,不傳的話是200
Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
request中放入請求狀態碼
3)、將我們的定製錯誤數據攜帶出去;
出現錯誤以後,會來到/error請求,會被BasicErrorController處理,響應出去可以獲取的數據是由getErrorAttributes得到的(是AbstractErrorController(ErrorController)規定的方法);
1、完全來編寫一個ErrorController的實現類【或者是編寫AbstractErrorController的子類】,放在容器中;
2、頁面上能用的數據,或者是json返回能用的數據都是通過errorAttributes.getErrorAttributes得到;
容器中DefaultErrorAttributes.getErrorAttributes();默認進行數據處理的;
查看AbstractErrorController
protected Map<String, Object> getErrorAttributes(HttpServletRequest request, boolean includeStackTrace) {
WebRequest webRequest = new ServletWebRequest(request);
return this.errorAttributes.getErrorAttributes(webRequest, includeStackTrace);
}
給容器中加入我們自己定義的ErrorAttributes
@Component
public class MyErrorAttributes extends DefaultErrorAttributes {
/*給容器中加入我們自己定義的ErrorAttributes
* @Author: jiatp
* Description:返回值的map就是頁面和json獲取的所有字段
*/
@Override
public Map<String, Object> getErrorAttributes(WebRequest webRequest, boolean includeStackTrace) {
Map<String, Object> map =super.getErrorAttributes(webRequest, includeStackTrace);
map.put("company","jiatp");
//我們異常處理器攜帶的數據
Map<String,Object> ext =(Map) webRequest.getAttribute("ext",0);
map.put("ext",ext);
return map;
}
}
返回值的map就是頁面和json獲取的所有字段,最終的效果:響應是自適應的,可以通過定製ErrorAttributes改變需要返回的內容。