EMC
EMC

Reputation: 1930

How should I combine completable futures and try/catch in Java?

I have a method that combines the results of two other methods, one which is synchronous and throws an exception if something goes wrong, and one which returns a completable future, which completes with an exception if something goes wrong. I would like the consumer of my method to not have to deal with catching synchronous and async exceptions in two separate places, is there a decent way I can combine them into one exception output?

Upvotes: 2

Views: 1411

Answers (2)

michid
michid

Reputation: 10814

In addition to wrapping the synchronous method call into a CompletableFuture as suggested by Matt there is CompletableFuture.thenCompose for composing the results of the two individual futures.

Upvotes: 0

Matt Timmermans
Matt Timmermans

Reputation: 59174

If you want your outer method to return a CompletableFuture, then it's usually best if it always returns a CompletableFuture -- no throws and no nulls.

That way, the caller only has to handle exceptions or nulls through one path.

When the outer method makes the synchronous call, make sure it's in a try block, catch any exception and return an exceptionally completed CompletableFuture for it.

If you're using java 9 or better, you can use CompletableFuture.failedFuture to make the error future. Otherwise you should probably make a helper method that makes a new future and calls completeExceptionally on it right away.

Upvotes: 3

Related Questions