十一、springboot異常處理
阿新 • • 發佈:2018-12-22
1.自定義錯誤頁面
SpringBoot 預設的處理異常的機制:SpringBoot 預設的已經提供了一套處理異常的機制。 一旦程式中出現了異常 SpringBoot 會像/error 的 url 傳送請求。在 springBoot 中提供了一個 叫 BasicExceptionController 來處理/error 請求,然後跳轉到預設顯示異常的頁面來展示異常 資訊。
如 果 我 們 需 要 將 所 有 的 異 常 同 一 跳 轉 到 自 定 義 的 錯 誤 頁 面 , 需 要 再 src/main/resources/templates 目錄下建立 error.html 頁面。注意:名稱必須叫 error
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.w3.org/1999/xhtml"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> 自定義錯誤頁面<br/> <span th:text="${exception}"></span> </body> </html>
[email protected] 註解處理異常
@Controller public class ExcetionController { @RequestMapping(value = "/show") public String showInfo(){ String str=null; str.length(); return "index"; } @RequestMapping(value = "/show2") public String showInfo2(){ int a=10/0; return "index"; } /** * java.lang.ArithmeticException.class * 只會處理當前controller的異常 * @return */ @ExceptionHandler(value ={java.lang.ArithmeticException.class,java.lang.NullPointerException.class}) public ModelAndView exception(Exception e){ ModelAndView mv=new ModelAndView(); mv.addObject("error",e.toString()); mv.setViewName("error1"); return mv; } }
error1.html
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.w3.org/1999/xhtml"> <head> <meta charset="UTF-8"> <title>ArithmeticException</title> </head> <body> <span th:text="${error}"></span> </body> </html>
[email protected][email protected]註解處理異常
需要建立一個能夠處理異常的全域性異常類。在該類上需 要新增@ControllerAdvice 註解
@ControllerAdvice public class GlobalException { /** * java.lang.ArithmeticException.class * @return */ @ExceptionHandler(value ={java.lang.ArithmeticException.class,java.lang.NullPointerException.class}) public ModelAndView exception(Exception e){ ModelAndView mv=new ModelAndView(); mv.addObject("error",e.toString()); mv.setViewName("error1"); return mv; } }
4.配置SimpleMappingExceptionResolver處理異常
@Configuration public class GlobalException { @Bean public SimpleMappingExceptionResolver getSimpleMappingExceptionResolver(){ SimpleMappingExceptionResolver resolver=new SimpleMappingExceptionResolver(); Properties properties=new Properties(); //引數1:異常的型別,注意必須是異常的全名 //引數2:檢視名稱 //無法傳遞異常資訊 properties.put("java.lang.ArithmeticException","error1"); properties.put("java.lang.NullPointerException","error1"); resolver.setExceptionMappings(properties); return resolver; } }
5.自定義HandlerExceptionResolver類處理異常
@Configuration public class GlobalException implements HandlerExceptionResolver { @Override public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) { ModelAndView mv=new ModelAndView(); if (e instanceof ArithmeticException){ mv.setViewName("error1"); } if (e instanceof NullPointerException){ mv.setViewName("error1"); } mv.addObject("error",e.toString()); return mv; } }