Created
November 8, 2016 17:36
-
-
Save mrsarm/8092bf0fbc3e01433b77de6e35af923c to your computer and use it in GitHub Desktop.
Java 8+ CompletableFuture example with error handling
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
CompletableFuture.supplyAsync(()-> { | |
try { | |
Thread.sleep(5000); | |
} catch (InterruptedException e) { | |
throw new RuntimeException("Error sleeping", e); | |
} | |
if (System.currentTimeMillis()%2==0) { | |
throw new RuntimeException("Even time..."); // 50% chance to fail | |
} | |
return "Hello World!"; | |
}) | |
.thenAcceptAsync(s-> { | |
System.out.println("Result: " + s); | |
}) | |
.exceptionally(e-> { | |
System.err.println("Error greeting: " + e.getMessage()); | |
return null; | |
}); |
@mrsarm is it possible to throw the exception to the caller?
@gaurav9822 no, because it's async code, but if you are building a "service" class and you want the caller to take care of the errors, you should remove the exceptionally
block and maybe the thenAcceptAsync
block, and return the CompletableFuture
object returned by supplyAsync
, so once the caller call your service method, it can handle the exception. Eg.
public CompletableFuture getGreeting() {
return CompletableFuture.supplyAsync(()-> "Hello World");
}
Then in the caller:
getGreeting().
.thenAcceptAsync(s-> {
// Do whatever needs to do the caller with the result s
System.out.println("Result: " + s);
})
.exceptionally(e-> {
// Handle the exeption, the caller way...
System.err.println("Error greeting: " + e.getMessage());
return null;
});
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
well done