How to throw exception in main thread when CompletableFuture finished exceptionally immediately

44 views Asked by At

When my service is called, I have 2 @Async FeignClient APIs getBookAsync, getAuthorAsync to check things:

@Async
public CompletableFuture<JsonNode> getBookAsync(Long id) {
    CompletableFuture<JsonNode> future = new CompletableFuture<>();
    try {
        future.complete(bookClient.getBook(id));
    } catch (Exception e) {
        future.completeExceptionally(e);
    }
    return future; }

getAuthorAsync is the same as above.

Then if both of the checks is correct, I will save the record it:

CompletableFuture.allOf(bookFuture, authorFuture)
    .thenRun(() -> recordRepository.save(record));

I want to throw the error that bookClient.getBook(id) thrown immediately in the main thread if there's one because there's no reason to check author if book already failed.

The error will be handle by a global exception handler.

0

There are 0 answers