如何使用 Spring Boot 实现异常处理?
-
使用 @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"; } } -
使用 @ControllerAdvice + @ExceptionHandler 注解处理全局异常(value后面可以填写数组)
@ControllerAdvice public class ControllerAdviceException { @ExceptionHandler(value = {NullPointerException.class}) public String NullPointerExceptionHandler(Model model, Exception e) { model.addAttribute("message", "@ControllerAdvice + @ExceptionHandler :" + e.getMessage()); return "index"; } } -
配置 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; } } -
实现 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; } }

本文详细介绍了在SpringBoot中如何使用@ExceptionHandler、@ControllerAdvice、SimpleMappingExceptionResolver及实现HandlerExceptionResolver接口等四种方式来处理异常,每种方式都有其适用场景和优缺点。

被折叠的 条评论
为什么被折叠?



