SpringBoot 異常處理
阿新 • • 發佈:2018-12-18
SpringBoot 異常處理
一、自定義錯誤頁面
建立 error.html 頁面,當發生錯誤時,將自動跳轉到該頁面。內部實現類為:BasicErrorController
適用範圍:所有的異常都指向 error.html 頁面,不能根據對應的異常跳轉到對應的頁面。
二、@ExceptionHandler
在對應的Controller內,新增對應的錯誤處理方法,然後跳轉到指定的錯誤頁面。
適用範圍:每個Controller內都有對應的錯誤方法,程式碼冗餘性高。
三、@ControllerAdvice 全域性異常處理器註解
搭配@ExceptionHandler 使用,可以解決方式二的程式碼冗餘問題。
四、SimpleMappingExceptionResolver
@Configuration //當配置類使用 public class GlobalException { @Bean //返回異常處理bean public SimpleMappingExceptionResolver getGlobalException() { SimpleMappingExceptionResolver smer = new SimpleMappingExceptionResolver(); Properties mappingsView Code= new Properties(); mappings.put("異常型別", "檢視名稱"); smer.setExceptionMappings(mappings); return smer; } }
適用範圍:區別於方式三,方式四無法傳遞異常物件。
五、HandlerExceptionResolver
實現 HandlerExceptionResolver,重寫 resolveException 方法
@ConfigurationView Codepublic class GlobalException extends HandlerExceptionResolverComposite{ @Override public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { ModelAndView mv = new ModelAndView(); //新增異常分支處理 if(ex instanceof NullPointerException) { mv.setViewName("檢視名稱"); } if(ex instanceof ArithmeticException) { mv.setViewName("檢視名稱"); } mv.addObject("error", ex.toString()); //傳遞異常物件 return mv; } }
適用範圍:與方式三類似。