Skip to content
Original file line number Diff line number Diff line change
Expand Up @@ -316,17 +316,20 @@ public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
Response response = null;
IOException lastException = null;
boolean responseReturned = false;

try {
for (int attempt = 0; attempt <= maxRetries; attempt++) {
try {
if (response != null) {
response.close();
response = null;
}
response = chain.proceed(request);

// Don't retry on successful responses or client errors (4xx)
if (response.isSuccessful() || response.code() < 500) {
responseReturned = true;
return response;
}

Expand Down Expand Up @@ -365,10 +368,12 @@ public Response intercept(Chain chain) throws IOException {
throw lastException;
}

responseReturned = true;
return response;
} finally {
// Ensure response is closed if we're not returning it successfully
if (response != null && (lastException != null || !response.isSuccessful())) {
// Keep the response open for the caller to consume, including final error
// responses.
if (response != null && !responseReturned) {
response.close();
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -742,6 +742,36 @@ void testHttp503ServiceUnavailable() {
assertTrue(exception.getMessage().contains("server error"));
}

@Test
void testRetryKeepsFinalErrorResponseBodyReadable() {
mockWebServer.enqueue(
new MockResponse()
.setResponseCode(500)
.setBody("{\"message\": \"first failure\"}"));
mockWebServer.enqueue(
new MockResponse()
.setResponseCode(500)
.setBody("{\"message\": \"final failure\"}"));

RAGFlowConfig config =
RAGFlowConfig.builder()
.apiKey("test-api-key")
.baseUrl(mockWebServer.url("").toString().replaceAll("/$", ""))
.addDatasetId("dataset-123")
.maxRetries(1)
.build();

RAGFlowClient client = new RAGFlowClient(config);

RAGFlowApiException exception =
assertThrows(
RAGFlowApiException.class,
() -> client.retrieve("test query", null, null, null).block());

assertTrue(exception.getMessage().contains("final failure"));
assertEquals(2, mockWebServer.getRequestCount());
}

@Test
void testApiErrorWithNonZeroCode() {
String errorResponse =
Expand Down
Loading