自定義錯(cuò)誤頁(yè)面
????????SpringBoot默認(rèn)的處理異常的機(jī)制:SpringBoot 默認(rèn)的已經(jīng)提供了一套處理異常的機(jī)制。一旦程序中出現(xiàn)了異常 SpringBoot 會(huì)向/error 的 url 發(fā)送請(qǐng)求。在 springBoot 中提供了一個(gè)叫 BasicErrorController 來處理/error 請(qǐng)求,然后跳轉(zhuǎn)到默認(rèn)顯示異常的頁(yè)面來展示異常信息。
如 果我 們 需 要 將 所 有 的 異 常 同 一 跳 轉(zhuǎn) 到 自 定 義 的 錯(cuò) 誤 頁(yè) 面 , 需 要 再src/main/resources/
templates 目錄下創(chuàng)建 error.html 頁(yè)面。注意:名稱必須叫 error
controller
/**
* SpringBoot處理異常方式一:自定義錯(cuò)誤頁(yè)面
*/
@Controller
public class DemoController {
@RequestMapping("/show")
public String showInfo(){
String str = null;
str.length();
return "index";
}
@RequestMapping("/show2")
public String showInfo2(){
int a = 10/0;
return "index";
}
}
?文章來源地址http://www.zghlxwxcb.cn/news/detail-797800.html
錯(cuò)誤頁(yè)面
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>錯(cuò)誤提示頁(yè)面</title>
</head>
<body>
出錯(cuò)了,請(qǐng)與管理員聯(lián)系。。。
<span th:text="${error}"></span>
</body>
</html>
整合web訪問全局異常處理器
處理思路
?
創(chuàng)建全局異常處理器
/**
* 通過實(shí)現(xiàn)HandlerExceptionResolver接口做全局異常處理
*/
@Component
public class GlobleException implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
ModelAndView modelAndView = new ModelAndView();
if (e instanceof ArithmeticException) {
modelAndView.setViewName("error1");
} else if (e instanceof NullPointerException) {
modelAndView.setViewName("error2");
}
modelAndView.addObject("error", e.toString());
return modelAndView;
}
}
?
錯(cuò)誤頁(yè)面
error1.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>錯(cuò)誤提示頁(yè)面-ArithmeticException</title>
</head>
<body>
出錯(cuò)了,請(qǐng)與管理員聯(lián)系。。。
<span th:text="${error}"></span>
</body>
</html>
? ?
error2.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>錯(cuò)誤提示頁(yè)面-NullPointerException</title>
</head>
<body>
出錯(cuò)了,請(qǐng)與管理員聯(lián)系。。。
<span th:text="${error}"></span>
</body>
</html>
整合ajax全局異常處理
創(chuàng)建全局異常處理器
@ControllerAdvice
public class AjaxGlobleException {
@ResponseBody
@ExceptionHandler
/**
* 處理全局異常
* @param exception 異常
* @return Map<String, Object>
*/
public Map errorHandler(Exception e) {
HashMap<String, Object> map = new HashMap<>();
map.put("status", 500);
map.put("msgs", e.toString());
return map;
}
}
?文章來源:http://www.zghlxwxcb.cn/news/detail-797800.html
?
到了這里,關(guān)于Spring Boot異常處理的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!