Nick
Nick

Reputation: 2970

Join completable future to current thread on exception

I have a method call that dispatches a request and asynchronously waits for the response. Once a response comes in, it fires a callback to process the result.

However, if something fails (wrong response or some other failure) I want to rethrow the exception in the calling thread.

dispatcher.dispatch(json)
.whenComplete((responseString, throwable) -> responses.handle(responseString));

Rethrowing the exception in the lambda expression will obviously not work, since it's in a different thread. So something along the lines of

dispatcher.dispatch(json)
.whenComplete((responseString, throwable) -> responses.handle(responseString))
.joinExceptionally(throwable -> throw throwable);

This call can not be blocking either. In other words, is it possible to throw an exception in the calling thread once the completable future completes exceptionally, without blocking?

Upvotes: 0

Views: 687

Answers (1)

haoyu wang
haoyu wang

Reputation: 1377

That's basically impossible.

You want to handle the request asynchronously, so the request must be handled in another thread. You alse want the Exception to be thrown in the calling thread so the exception must be thrown in the same thread (because exception are propagated through the call stack) which contract to previous requirement.

Usually a dispatcher is use only for dispatching request, it should not be used to handle exceptions.You'd better use CompletableFuture's built in feature to handle excepitons like CompletableFuture.handle(BiFunction<? super T, Throwable, ? extends U> fn).

Upvotes: 1

Related Questions