异常相关参数-demo
接下来我们来测试一下这些异常参数,我们首先在项目里面定义两个异常类BusinessException和ParamException,其中ParamException是BusinessException的子类
// 定义一个统一的业务异常类
public class BusinessException extends RuntimeException{
public BusinessException(String message) {
super(message);
}
}
// 定义一个参数异常处理类,是业务异常类的子类
public class ParamException extends BusinessException{
public ParamException(String message) {
super(message);
}
}
我们首先抛出一个非指定的异常,观察下是否会发生重试,这个案例中我们依然抛出一个ArithmeticException异常,但是我们只指定当遇到ParamException异常时才会进行重试。
@Retryable(scene = "localRetryIncludeException",include = ParamException.class)
public void localRetryIncludeException(){
System.out.println("local retry include exception 方法开始执行");
double i = 1 / 0;
}
运行后观察控制台我们可以看到,仅执行了一次,并未进行重试
接下来我们抛出指定异常,例如抛出自定义的ParamException异常,观察是否会重试。
@Retryable(scene = "localRetryIncludeException",include = ParamException.class)
public void localRetryIncludeException(){
System.out.println("local retry include exception 方法开始执行");
throw new ParamException("此处发生了指定异常Param Exception");
}
运行方法后我们观察控制台,看到方法发生了重试。
当然,由于ParamException是BusinessException的子类,当我们指定处理的类是父类BusinessException时,同样也会进行重试。这样子我们就可以通过自定义异常来指定某些特定报错的业务场景才执行重试逻辑,同时如果也可以通过指定异常的继承关系对一类异常场景进行统一的处理。
@Retryable(scene = "localRetryIncludeException",include = BusinessException.class)
public void localRetryIncludeException(){
System.out.println("local retry include exception 方法开始执行");
throw new ParamException("此处发生了指定异常Param Exception");
// throw new NullPointerException();
}
接下来我们看exclude参数,这个参数和include是相反的,include是遇到指定的异常就重试,而exclude是遇到指定的异常就不重试。 我们直接给出案例
@Retryable(scene = "localRetryExcludeException",exclude = {ParamException.class,ArithmeticException.class})
public void localRetryExcludeException(){
System.out.println("local retry exclude exception 方法开始执行");
double i = 1 / 0;
throw new ParamException("此处发生了参数异常");
}
观察控制台输出,我们可以看到没有进行重试就抛出了对应的异常
接下来我们讲解isThrowException参数,这个参数比较简单,表示我们在进行重试动作后是否会将异常抛出来,我们给出一个案例,在这个案例中我们继续在上一个exclude参数中一个未测试到的场景,此时我们指定exclude的参数为ArithmeticException,然后再指定isThrowException的值为false。
@Retryable(scene = "localRetryIsThrowException",exclude = ArithmeticException.class,isThrowException = false)
public void localRetryIsThrowException(){
System.out.println("local retry is throw exception 方法开始执行");
throw new ParamException("此处发生了参数异常");
}
此时我们观察服务台输出,可以看到由于指定的异常,并不在我们抛出异常的列表中。因此发生了重试,大家可以看到异常的信息,依然是打印出来的,但是在此处,整个测试案例就是通过了的。这也就意味着上游调用这个接口的服务方并不会感知到本次异常的发生。 因此,isThrowException参数会屏蔽本次异常的发生,而不是向上抛出异常。