sometimes we get this exception handling Response.
It seems that Response has a null
body.
The code is something like:
try (Response response = client.newCall(request).execute()) {
// do stuff with the response
} catch (Exception e) {
log.error("Something wrong", e);
}
The exception is raised on the close()
method automatically called on the Response, after the do stuff with response
block went executed.
Stack trace:
java.lang.IllegalStateException: response is not eligible for a body and must not be closed
at okhttp3.Response.close(Response.java:281)
Are we missing something?
Thanks.
I think u can invoke response.body.close()
which is the same as response.close()
, and check body is null or not before close.
ResponseBody responseBody = null;
try {
Response response = client.newCall(request).execute();
responseBody = response.body();
// do stuff with the response
} catch (Exception e) {
log.error("Something wrong", e);
} finally {
if (responseBody != null) {
responseBody.close();
}
}
Since the Try with Resources works with Auto-closable (ie classes implement the Closable interface, it tries to call close automatically after the block.
Now the spec for Response close() method, does specify the method would throw and exception in certain cases.
It is an error to close a response that is not eligible for a body. This includes the responses returned from {@link #cacheResponse}, {@link #networkResponse}, and {@link priorResponse()}.
Source: https://github.com/square/okhttp/blob/master/okhttp/src/main/java/okhttp3/Response.java
So, it is 'expected' you can just log the details and continue if it is expected. OR handle appropriately (eg: retry) if it is not expected..
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With