如何使用Spring Boot实现异常处理?
1. 使用@ExceptionHandler注解处理局部异常,该方式只能处理当前controller中的ArithmeticException和NullPointerException异常,缺点就是只能处理单个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", "没有抛出异常"); 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 类处理异常 @Configuration public class SimpleMappingException { @Bean public SimpleMappingExceptionResolver getSimpleMappingExceptionResolver(){ SimpleMappingExceptionResolver resolver = new SimpleMappingExceptionResolver(); Properties mappings = new Properties(); //个参数为异常全限定名,第二个为跳转视图名称 mappings.put("java.lang.NullPointerException", "index"); mappings.put("java.lang.ArithmeticException", "index"); //设置异常与视图映射信息的 resolver.setExceptionMappings(mappings); return resolver; } }
4. 实现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", "实现HandlerExceptionResolver接口");
//判断不同异常类型,做不同视图跳转 if(ex instanceof NullPointerException){ modelAndView.setViewName("index"); } if(ex instanceof ArithmeticException){ modelAndView.setViewName("index"); } return modelAndView; } }