- SpringBoot 異常處理方式
SpringBoot 中對於異常處理提供了五種處理方式:
- 自定義錯誤頁面
SpringBoot 默認的處理異常的機制:SpringBoot 默認的已經提供了一套處理異常的機制。
一旦程序中出現了異常 SpringBoot 會像/error 的 url 發送請求。在 springBoot 中提供了一個叫 BasicExceptionController 來處理/error 請求,然後跳轉到默認顯示異常的頁面來展示異常
信息.
如 果 我 們 需 要 將 所 有 的 異 常 同 一 跳 轉 到 自 定 義 的 錯 誤 頁 面 , 需 要 再 src/main/resources/templates 目錄下創建 error.html 頁面。注意:名稱必須叫 error |
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>錯誤提示頁面</title>
</head>
<body>
出錯了,請與管理員聯繫。。。
<span th:text="${exception}"></span>
</body>
</html>
- @ExceptionHandle 註解處理異常
/**
* SpringBoot處理異常方式一:自定義錯誤頁面
*
*
*/
@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";
}
/**
* java.lang.ArithmeticException
* 該方法需要返回一個ModelAndView:目的是可以讓我們封裝異常信息以及視圖的指定
* 參數Exception e:會將產生異常對象注入到方法中
*/
@ExceptionHandler(value={java.lang.ArithmeticException.class})
public ModelAndView arithmeticExceptionHandler(Exception e){
ModelAndView mv = new ModelAndView();
mv.addObject("error", e.toString());
mv.setViewName("error1");
return mv;
}
/**
* java.lang.NullPointerException
* 該方法需要返回一個ModelAndView:目的是可以讓我們封裝異常信息以及視圖的指定
* 參數Exception e:會將產生異常對象注入到方法中
*/
@ExceptionHandler(value={java.lang.NullPointerException.class})
public ModelAndView nullPointerExceptionHandler(Exception e){
ModelAndView mv = new ModelAndView();
mv.addObject("error", e.toString());
mv.setViewName("error2");
return mv;
}
}
============================================
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>錯誤提示頁面-NullPointerException</title>
</head>
<body>
出錯了,請與管理員聯繫。。。
<span th:text="${error}"></span>
</body>
</html>
- 3.@ControllerAdvice+@ExceptionHandler 處理異常
需要創建一個能夠處理異常的全局異常類。 。 在該類上需要添加@ControllerAdvice 註解
/**
* 全局異常處理類
*
*
*/
@ControllerAdvice
public class GlobalException {
/**
* java.lang.ArithmeticException
* 該方法需要返回一個ModelAndView:目的是可以讓我們封裝異常信息以及視圖的指定
* 參數Exception e:會將產生異常對象注入到方法中
*/
@ExceptionHandler(value={java.lang.ArithmeticException.class})
public ModelAndView arithmeticExceptionHandler(Exception e){
ModelAndView mv = new ModelAndView();
mv.addObject("error", e.toString());
mv.setViewName("error1");
return mv;
}
/**
* java.lang.NullPointerException
* 該方法需要返回一個ModelAndView:目的是可以讓我們封裝異常信息以及視圖的指定
* 參數Exception e:會將產生異常對象注入到方法中
*/
@ExceptionHandler(value={java.lang.NullPointerException.class})
public ModelAndView nullPointerExceptionHandler(Exception e){
ModelAndView mv = new ModelAndView();
mv.addObject("error", e.toString());
mv.setViewName("error2");
return mv;
}
}
- 4.配置SimpleMappingExceptionResolver
在全局異常類中添加一個方法完成異常的統一處理
/**
* 通過SimpleMappingExceptionResolver做全局異常處理
*
*
*/
@Configuration
public class GlobalException {
/**
* 該方法必須要有返回值。返回值類型必須是:SimpleMappingExceptionResolver
*/
@Bean
public SimpleMappingExceptionResolver getSimpleMappingExceptionResolver(){
SimpleMappingExceptionResolver resolver = new SimpleMappingExceptionResolver();
Properties mappings = new Properties();
/**
* 參數一:異常的類型,注意必須是異常類型的全名
* 參數二:視圖名稱
*/
mappings.put("java.lang.ArithmeticException", "error1");
mappings.put("java.lang.NullPointerException","error2");
//設置異常與視圖映射信息的
resolver.setExceptionMappings(mappings);
return resolver;
}
}
- 4.配置SimpleMappingExceptionResolver
在全局異常類中添加一個方法完成異常的統一處理
/**
* 通過SimpleMappingExceptionResolver做全局異常處理
*
*
*/
@Configuration
public class GlobalException {
/**
* 該方法必須要有返回值。返回值類型必須是:SimpleMappingExceptionResolver
*/
@Bean
public SimpleMappingExceptionResolver getSimpleMappingExceptionResolver(){
SimpleMappingExceptionResolver resolver = new SimpleMappingExceptionResolver();
Properties mappings = new Properties();
/**
* 參數一:異常的類型,注意必須是異常類型的全名
* 參數二:視圖名稱
*/
mappings.put("java.lang.ArithmeticException", "error1");
mappings.put("java.lang.NullPointerException","error2");
//設置異常與視圖映射信息的
resolver.setExceptionMappings(mappings);
return resolver;
}
}
- 5.自定義 HandlerExceptionResolver 類處理異常
需要在全局異常處理類中實現 HandlerExceptionResolver
/**
* 通過實現HandlerExceptionResolver接口做全局異常處理
*
*
*/
@Configuration
public class GlobalException implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
Exception ex) {
ModelAndView mv = new ModelAndView();
//判斷不同異常類型,做不同視圖跳轉
if(ex instanceof ArithmeticException){
mv.setViewName("error1");
}
if(ex instanceof NullPointerException){
mv.setViewName("error2");
}
mv.addObject("error", ex.toString());
return mv;
}
}
異常信息入庫:
@Slf4j
@Aspect
@Component
public class ExceptionLogAspect {
@Autowired
private ExceMapper exceMapper;
@Pointcut("execution(* cc.mrbird.febs.common.handler.GlobalExceptionHandler.*(..) )")
public void pointcut(){}
@Before("pointcut()")
public void addInfo(JoinPoint joinPoint )
{
ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
HttpServletRequest request = servletRequestAttributes.getRequest();
Object[] args = joinPoint.getArgs();
Exception ex = (Exception) args[0];
// 將異常信息寫入數據庫
StringWriter sw = new StringWriter();
ex.printStackTrace(new PrintWriter(sw, true));
ExcetionMessage excetionMessage = new ExcetionMessage();
excetionMessage.setOperTime(new Date());
excetionMessage.setMessage(ex.getMessage());
excetionMessage.setExecption(sw.toString());
exceMapper.insert(excetionMessage);
}
}