简化 retryInterceptor
之前:
@Override
public Response intercept(Chain chain) throws IOException {
final Request request = chain.request();
IOException savedException = null;
Response response = null;
// 总尝试次数 = maxRetries + 1
for (int attempt = 0; attempt <= maxRetries; attempt++) {
try {
response = chain.proceed(request);
// 处理服务端5xx错误
if (response.code() >= 500) {
if (attempt < maxRetries) {
closeQuietly(response);
waitWithExponentialBackoff(attempt, baseDelayMs, checkIdempotent);
continue; // 继续重试
}
return response; // 最后一次返回非成功响应
}
return response; // 成功响应
} catch (IOException e) {
savedException = e;
if (isRetryable(e)) {
if (attempt < maxRetries) {
// 如果是SSL握手错误,静默重试而不抛出异常
if (e instanceof SSLHandshakeException) {
waitWithExponentialBackoff(attempt, baseDelayMs, checkIdempotent);
continue;
}
waitWithExponentialBackoff(attempt, baseDelayMs, checkIdempotent);
continue; // 继续重试
}
// 达到最大重试次数后,如果是SSL握手错误,仅返回自定义消息(不包含原始异常)
if (e instanceof SSLHandshakeException) {
throw new IOException("Connection failed after " + maxRetries + " retries");
}
}
throw e; // 达到最大重试次数或不可重试异常
}
}
// 保底异常处理(理论上不会执行到这里)
throw savedException != null ? savedException
: new IOException("Request failed after " + maxRetries + " retries");
}
简化:
@Override
public Response intercept(Chain chain) throws IOException {
final Request request = chain.request();
Response response = null;
for (int attempt = 0; attempt <= maxRetries; attempt++) {
try {
response = chain.proceed(request);
// 处理服务端5xx错误
if (response.code() >= 500 && attempt < maxRetries) {
closeQuietly(response);
waitWithExponentialBackoff(attempt, baseDelayMs, checkIdempotent);
continue; // 继续重试
}
return response; // 返回响应(无论成功或最后一次失败)
} catch (IOException e) {
if (isRetryable(e) && attempt < maxRetries) {
waitWithExponentialBackoff(attempt, baseDelayMs, checkIdempotent);
continue; // 继续重试
}
// 所有异常统一包装,不泄露原始堆栈
throw new IOException("Request failed after " + maxRetries + " retries");
}
}
// 理论上不会执行到这里(因为循环内已覆盖所有情况)
throw new IOException("Request failed after " + maxRetries + " retries");
}
浙公网安备 33010602011771号