统一异常处理
-
程序中有异常,默认情况下会报500的错误,现在想让他不出现500,而是出现统一的提示
-
由于要用到R对象,因此在service_base模块中添加依赖
<dependency> <groupId>com.atguigu</groupId> <artifactId>common_utils</artifactId> <version>0.0.1-SNAPSHOT</version> </dependency>
-
依赖传递
问题:由于之前在service模块中引入了service_base和common_utils这两个依赖,而service_base中也引入了 common_utils依赖,造成common_utils多次引入 解决:service模块不需要在引入common_utils依赖了,只引入service_base就足够了,因为service_base 里面引入了common_utils
-
在service-base模块中,创建包com.atguigu.servicebase.exceptionhandler,在包exceptionhandler里创建统一异常处理类GlobalExceptionHandler
@ControllerAdvice // @ControllerAdvice配合@ExceptionHandler实现异常处理 public class GlobalExceptionHandler { @ExceptionHandler(Exception.class) // 指定出现什么异常执行这个方法,这里所有异常都会执行 @ResponseBody // 为了返回数据(controller中有@RestController,因此数据才可以返回) public R error(Exception e) { e.printStackTrace(); return R.error().message("执行了全局异常处理.."); } @ExceptionHandler(ArithmeticException.class) // ArithmeticException异常会执行 @ResponseBody public R error(ArithmeticException e) { e.printStackTrace(); return R.error().message("执行了ArithmeticException异常处理.."); } }
-
既有特定异常,又有全局异常,如果出现了特定异常,执行特定异常处理,否则执行全局异常处理
自定义异常处理
-
在包exceptionhandler里创建自定义异常类GuliException
@Data // 生成属性的get、set方法 @AllArgsConstructor // 生成类的有参构造方法 @NoArgsConstructor // 生成类的无参构造方法 public class GuliException extends RuntimeException { private Integer code; // 状态码 private String msg; // 异常信息 }
-
在统一异常处理类GlobalExceptionHandler中添加方法
@ExceptionHandler(GuliException.class) // 自定义异常 @ResponseBody public R error(GuliException e) { e.printStackTrace(); return R.error().code(e.getCode()).message(e.getMsg()); }
-
自定义异常系统不会自动抛出,需要手动抛出
try { int i = 10 / 0; } catch (Exception e) { throw new GuliException(20001, "执行了自定义异常处理...."); // 执行自定义异常 }