1. 使用@ExceptionHandler注解處理局部異常,該方式只能處理當(dāng)前controller中的ArithmeticException和NullPointerException異常,缺點(diǎn)就是只能處理單個(gè)controller的異常。
@Controller public class ExceptionHandlerController { @RequestMapping("/excep") public String exceptionMethod(Model model) throws Exception { String a=null; System.out.println(a.charAt(1)); int num = 1/0; model.addAttribute("message", "沒(méi)有拋出異常"); return "index"; } @ExceptionHandler(value = {ArithmeticException.class,NullPointerException.class}) public String arithmeticExceptionHandle(Model model, Exception e) { model.addAttribute("message", "@ExceptionHandler" + e.getMessage()); return "index"; } }
2. 使用 @ControllerAdvice + @ExceptionHandler 注解處理全局異常 @ControllerAdvice public class ControllerAdviceException { @ExceptionHandler(value = {NullPointerException.class}) public String NullPointerExceptionHandler(Model model, Exception e) { model.addAttribute("message", "@ControllerAdvice + @ExceptionHandler :" + e.getMessage()); return "index"; } }
3. 配置 SimpleMappingExceptionResolver 類(lèi)處理異常 @Configuration public class SimpleMappingException { @Bean public SimpleMappingExceptionResolver getSimpleMappingExceptionResolver(){ SimpleMappingExceptionResolver resolver = new SimpleMappingExceptionResolver(); Properties mappings = new Properties(); //個(gè)參數(shù)為異常全限定名,第二個(gè)為跳轉(zhuǎn)視圖名稱(chēng) mappings.put("java.lang.NullPointerException", "index"); mappings.put("java.lang.ArithmeticException", "index"); //設(shè)置異常與視圖映射信息的 resolver.setExceptionMappings(mappings); return resolver; } }
4. 實(shí)現(xiàn)HandlerExceptionResolver接口處理異常@Configuration public class HandlerException implements HandlerExceptionResolver { @Override public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { ModelAndView modelAndView = new ModelAndView(); modelAndView.addObject("message", "實(shí)現(xiàn)HandlerExceptionResolver接口");
//判斷不同異常類(lèi)型,做不同視圖跳轉(zhuǎn) if(ex instanceof NullPointerException){ modelAndView.setViewName("index"); } if(ex instanceof ArithmeticException){ modelAndView.setViewName("index"); } return modelAndView; } }