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

EMC :

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?

Matt Timmermans :

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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=130950&siteId=1