一、异常基础
异常分为两类:
① 未到达Controller,拦截器异常、404等
② 到达Controller,系统异常空指针等500异常
二、列举springBoot中常用的五种统一处理异常方式
-
自定义错误页面
springboot默认处理异常是当出现异常的时候,会找到内置的 /error 路径,返回错误信息。那么我们重写error.html页面,或者建立/resource/error目录,添加404.html,500.html静态页面。
目录结构
这里需要注意一点,名字必须一致,建目录时名字必须为/error,或者error.html。
缺点:拦截所有异常,不灵活 -
@ExceptionHandle 注解处理异常
在Controller类中添加拦截异常方法并使用 @ExceptionHandler 注解@RestController public class ExceptionHandler2 { @RequestMapping("/handler2/exception") public String index() { String s = null; s.length(); return "hello world!"; } /** * 用于拦截本类的java.lang.NullPointerException异常 * 该方法需要返回一个 ModelAndView:目的是可以让我们封装异常信息以及视图的指定 * 参数 Exception e:会将产生异常对象注入到方法中 */ @ExceptionHandler(value = NullPointerException.class) public ModelAndView nullExceptionHanlder(Exception e) { ModelAndView mv = new ModelAndView(); mv.addObject("error", "ExceptionHandler2: "+e.toString()); mv.setViewName("/handler/error"); return mv; } }
缺点:只对本类起作用,针对每种类型异常都要编码,代码冗余,工作量大。
-
@ControllerAdvice/@RestControllerAdvice+@ExceptionHandler 注解处理异常
首先新建统一处理类,GlobalException.java@RestControllerAdvice(basePackageClasses={ ExceptionHandler3.class}) public class GlobalException { private static String errorPath = "/handler/error"; /** * 用于拦截本类的java.lang.NullPointerException异常 * 该方法需要返回一个 ModelAndView:目的是可以让我们封装异常信息以及视图的指定 * 参数 Exception e:会将产生异常对象注入到方法中 */ @ExceptionHandler(value = NullPointerException.class) public ModelAndView nullExceptionHanlder(Exception e) { ModelAndView mv = new ModelAndView(); mv.addObject("error", "ExceptionHandler3: "+e.toString()); mv.setViewName(errorPath); return mv; } /** * 编写拦截其他异常的方法.... */ }
Controller.java
@RestController public class ExceptionHandler3 { @RequestMapping("/handler3/exception") public String index() { String s = null; s.length(); return "hello world!"; } }
-
@Configuration + 配置 SimpleMappingExceptionResolver 处理异常
GlobalException4Handler4.java@Configuration public class GlobalException4Handler4 { private static String errorPath = "/handler/error"; /** * 该方法必须要有返回值。返回值类型必须是: SimpleMappingExceptionResolver * @return */ @Bean public SimpleMappingExceptionResolver getSimpleMappingExceptionResolver() { SimpleMappingExceptionResolver resolver = new SimpleMappingExceptionResolver(); Properties properties = new Properties(); // 参数一:异常的类型,注意必须是异常类型的全名