Skip to content

异常处理

概述

考虑到在重试最终异常场景下,为了避免执行逻辑出现错误,使用Chance必须显式处理异常,ChanceException也特意被定义为非检查类型(Unchecked)异常。处理ChanceException的时候可以获取最后一次失败重试的明细信息。

用法详解

例如:

java
public static void main(String[] args) {
    Chance<String> chance = Chance.<String, Throwable>newBuilder()
            .withNeverRetry()
            .build();
    try {
        chance.call(() -> {
            throw new RuntimeException("Some exception");
        });
    } catch (ChanceException ce) {
        Attempt<?, ?> lastFailedAttempt = ce.getAttempt();
        RuntimeException re = (RuntimeException) lastFailedAttempt.rootCauseNow();
        System.out.printf("[%d]: %s\n", lastFailedAttempt.attemptTimes(), re.getMessage());
    }
}

上面的代码最终输出结果:

shell
[1]: Some exception

TIP

ChanceException中携带的Attempt能提供很多有用的方法,可以参考前面Attempt 属性小节。

贡献者

页面历史

Released under the MIT License.