英文:
Join completable future to current thread on exception
问题
我有一个方法调用,它会分派一个请求并异步等待响应。一旦收到响应,它会触发一个回调来处理结果。
然而,如果出现问题(错误的响应或其他故障),我想在调用线程中重新抛出异常。
dispatcher.dispatch(json)
.whenComplete((responseString, throwable) -> responses.handle(responseString));
在lambda表达式中重新抛出异常显然行不通,因为它在不同的线程中。因此可以考虑类似以下方式:
dispatcher.dispatch(json)
.whenComplete((responseString, throwable) -> responses.handle(responseString))
.joinExceptionally(throwable -> throw throwable);
这个调用也不能是阻塞的。换句话说,是否有可能在CompletableFuture异常完成后,在调用线程中抛出异常,而不阻塞?
英文:
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?
答案1
得分: 1
那基本上是不可能的。
您希望异步处理请求,因此请求必须在另一个线程中处理。您还希望异常在调用线程中被抛出,因为异常通过调用堆栈传播,所以异常必须在同一个线程中抛出,与先前的要求相一致。
通常,调度程序仅用于分派请求,不应用于处理异常。您最好使用CompletableFuture
的内置功能来处理异常,比如CompletableFuture.handle(BiFunction<? super T, Throwable, ? extends U> fn)
。
英文:
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)
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论