Skip to content

异常相关参数详解

快速开始

重试动作大多发生在程序遭遇异常的场景中,因此异常相关参数的配置是重试机制中的核心部分。通过合理配置,可以灵活控制哪些异常会触发重试、哪些异常应被排除,以及重试失败后是否抛出异常。

1 参数说明

参数描述默认值必须指定
include包含的异常
exclude排除的异常
isThrowException本地重试完成后是否抛出异常true

1.1 include(包含的异常)

  • 作用:指定哪些异常类型发生时会触发重试。
  • 说明:只有在 include 列表中的异常才会被重试。

1.2 exclude(排除的异常)

  • 作用:指定哪些异常类型发生时不会重试,即使它们在 include 列表中。
  • 说明:exclude 优先级高于 include,出现在 exclude 列表中的异常不会被重试。

1.3 isThrowException(是否抛出异常)

  • 作用:控制在重试次数耗尽后,是否将最后一次异常抛出。
  • 说明:为 true 时,重试失败后会抛出异常;为 false 时,重试失败后返回默认值或 null。

2. 配置与代码示例

2.1 异常类信息

java
// 统一业务异常类
public class BizException extends RuntimeException {
    public BusinessException(String message) {
        super(message);
    }
}

// 参数异常类,继承自业务异常
public class ParamException extends BusinessException {
    public ParamException(String message) {
        super(message);
    }
}

2.2 代码示例与说明

2.2.1 include参数示例

假设我们只希望在遇到BizException时才重试:

Java
 @Retryable(scene = SceneConstant.LOCAL_RETRY + "5",
         retryStrategy = RetryType.ONLY_LOCAL,
         include = {BizException.class})
 @Override
 public void localRetryIncludeException(String params) {
     System.out.println("local retry include exception 方法开始执行");
     throw new BizException("10001", "local retry include exception 方法执行异常");
 }
  • 结果:只执行一次,不会重试。

如果抛出指定的ParamException:

java
@Retryable(scene = "localRetryIncludeException", include = ParamException.class)
public void localRetryIncludeException() {
    System.out.println("local retry include exception 方法开始执行");
    throw new ParamException("此处发生了指定异常Param Exception");
}
  • 结果:会发生重试。

如果指定父类BusinessException,也会对其子类生效:

java
@Retryable(scene = "localRetryIncludeException", include = BusinessException.class)
public void localRetryIncludeException() {
    System.out.println("local retry include exception 方法开始执行");
    throw new ParamException("此处发生了指定异常Param Exception");
}

2.2.2 exclude参数示例

java
@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("此处发生了参数异常");
}
  • 结果:不会重试,直接抛出异常。

2.2.3 isThrowException参数示例

java
@Retryable(scene = "localRetryIsThrowException", exclude = ArithmeticException.class, isThrowException = false)
public void localRetryIsThrowException() {
    System.out.println("local retry is throw exception 方法开始执行");
    throw new ParamException("此处发生了参数异常");
}
  • 结果:重试后异常不会向上抛出,上游服务方不会感知到本次异常。

3. 最佳实践

  • 明确业务中哪些异常需要重试,哪些应立即终止。
  • 推荐只 include 业务可恢复的异常,exclude 明显不可恢复或参数类异常。
  • isThrowException 建议在关键链路开启,便于问题追踪。
  • 利用异常的继承体系,灵活指定一类异常的重试策略。