如果我要增加自定义异常记录呢
时间: 2023-10-11 18:08:16 浏览: 34
您可以扩展 `RetryWrapper` 类来记录自定义异常信息。以下是一个示例实现:
```java
public class RetryWrapper {
public static <T> T retry(int maxAttempts, Callable<T> callable) throws Exception {
int attempt = 0;
while (true) {
try {
return callable.call();
} catch (Exception e) {
if (++attempt >= maxAttempts) {
throw e;
}
logError(e, attempt);
}
}
}
private static void logError(Exception e, int attempt) {
// your code here to log the error with attempt number
System.out.println("Attempt " + attempt + " failed with error: " + e.getMessage());
}
}
```
在上述代码中,我们添加了一个私有静态方法 `logError` 来记录异常信息,包括尝试次数和异常消息。您可以根据需要更改此方法来记录异常信息。
调用示例:
```java
int result = RetryWrapper.retry(3, () -> {
// your code here
return someValue;
});
```
在上述示例中,我们向 `RetryWrapper.retry` 函数传递了一个 lambda 表达式,该表达式包含要重试的代码。如果出现异常,`RetryWrapper` 类将记录异常信息并重新尝试执行代码,最多重试 `maxAttempts` 次。