Kotlin和Java简单的重试代码 - Vlad


这是您无需任何其他库或代码依赖项即可重试部分代码的方式。如果需要更复杂的东西,推荐使用Resilience4j库,因为它提供了其他即用型功能。

public static <T> T executeWithRetry(Class<? extends Exception> exClass, Callable<T> callable) {
    try {
        return callable.call();
    } catch (Exception e) {
        if (exClass.isAssignableFrom(e.getClass())) {
            try {
                return callable.call();
            } catch (Exception e2) {
                throw new RuntimeException(e2);
            }
        } else {
            throw new RuntimeException(e);
        }
    }
}

用法:
为了方便起见,在这里用RuntimeExceptions来包装所有的Exceptions:

var restult = executeWithRetry(IllegalArgumentException.class, () -> {
    //code that returns result
});

Kotlin:

inline fun <reified E : Exception> executeWithRetry(call: () -> Unit) =
    try {
        call()
    } catch (e: Exception) {
        if (e is E) call() else throw e
    }

在这里,声明了一种我想要捕获的异常。这使得这个函数更可重用。由于语言限制,无法直接捕获参数化异常。一种解决方法是捕获所有异常并在之后使用条件表达式检查它们。

用法:

executeWithRetry <IllegalArgumentException> { 
    //这里有一些重要的代码
}