1,SpringBoot 中是BasicErrorController的基類來是實現錯誤的。
@Controller
@RequestMapping("KaTeX parse error: Expected '}', got 'EOF' at end of input: …ver.error.path:{error.path:/error}}")
public class BasicErrorController extends AbstractErrorController {}
在springboot項目中,我們可以直接在類中通過局部方法處理異常,也可以繼承BasicErrorController 來實現或通過@ControllerAdvice 註解做異常統一處理。在沒有做處理時,springboot有默認的錯誤處理機制——顯示默認的錯誤頁面;默認的響應json數據(包含異常發生時間,異常狀態,異常詳細信息,發生異常的請求路徑)。
SpringBoot異常的設計的原理
發生異常時,前端控制器調用全局異常處理器進行處理。
springboot默認錯誤處理機制:
源碼中定製錯誤的響應規則,默認/error請求爲錯誤請求;BasicErrorController,這個類是默認處理/error請求的,它包含errorHtml和error兩個方法,前者返回ModelAndView,後者返回json數據;DefaultErrorViewResolver,指定瀏覽器響應的錯誤頁面,發生異常時其中resolver方法會解析異常處理地址,得到與錯誤狀態碼對應的視圖。
BasicErrorController這個類裏面有兩個方法 errorHtml()和error()方法
@RequestMapping(produces = "text/html")
public ModelAndView errorHtml(HttpServletRequest request,
HttpServletResponse response) {
response.setStatus(getStatus(request).value());
Map<String, Object> model = getErrorAttributes(request,
isIncludeStackTrace(request, MediaType.TEXT_HTML));
return new ModelAndView("error", model);
}
@RequestMapping
@ResponseBody
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<Map<String, Object>>(body, status);
}
自定義異常處理:
1)直接在Controller做處理。在Controller處理異常的方法上加上@ExceptionHandler(需要處理的那些異常類);
2)通過@ControllerAdvice 註解來處理統一錯誤。自定義一個異常處理類加上@ControllerAdvice註解,通過@ExceptionHandler(指定異常類)觸發不同的處理方法。