Skip to content

Commit

Permalink
Cancel calls on unexpected exceptions (3.14.x branch)
Browse files Browse the repository at this point in the history
Closes: square#5151
  • Loading branch information
squarejesse committed Sep 27, 2019
1 parent c8833f6 commit 4471395
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 5 deletions.
17 changes: 12 additions & 5 deletions okhttp-tests/src/test/java/okhttp3/InterceptorTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -517,11 +517,12 @@ private void interceptorThrowsRuntimeExceptionSynchronous(boolean network) throw
}

/**
* When an interceptor throws an unexpected exception, asynchronous callers are left hanging. The
* When an interceptor throws an unexpected exception, asynchronous calls are canceled. The
* exception goes to the uncaught exception handler.
*/
private void interceptorThrowsRuntimeExceptionAsynchronous(boolean network) throws Exception {
addInterceptor(network, chain -> { throw new RuntimeException("boom!"); });
RuntimeException boom = new RuntimeException("boom!");
addInterceptor(network, chain -> { throw boom; });

ExceptionCatchingExecutor executor = new ExceptionCatchingExecutor();
client = client.newBuilder()
Expand All @@ -531,9 +532,15 @@ private void interceptorThrowsRuntimeExceptionAsynchronous(boolean network) thro
Request request = new Request.Builder()
.url(server.url("/"))
.build();
client.newCall(request).enqueue(callback);

assertThat(executor.takeException().getMessage()).isEqualTo("boom!");
Call call = client.newCall(request);
call.enqueue(callback);
RecordedResponse recordedResponse = callback.await(server.url("/"));
assertThat(recordedResponse.failure)
.hasMessage("canceled due to java.lang.RuntimeException: boom!");
assertThat(recordedResponse.failure).hasSuppressedException(boom);
assertThat(call.isCanceled()).isTrue();

assertThat(executor.takeException()).isEqualTo(boom);
}

@Test public void applicationInterceptorReturnsNull() throws Exception {
Expand Down
8 changes: 8 additions & 0 deletions okhttp/src/main/java/okhttp3/RealCall.java
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,14 @@ void executeOn(ExecutorService executorService) {
} else {
responseCallback.onFailure(RealCall.this, e);
}
} catch (Throwable t) {
cancel();
if (!signalledCallback) {
IOException canceledException = new IOException("canceled due to " + t);
canceledException.addSuppressed(t);
responseCallback.onFailure(RealCall.this, canceledException);
}
throw t;
} finally {
client.dispatcher().finished(this);
}
Expand Down

0 comments on commit 4471395

Please sign in to comment.