Skip to content

Instantly share code, notes, and snippets.

@mrsarm
Created November 8, 2016 17:36
Show Gist options
  • Save mrsarm/8092bf0fbc3e01433b77de6e35af923c to your computer and use it in GitHub Desktop.
Save mrsarm/8092bf0fbc3e01433b77de6e35af923c to your computer and use it in GitHub Desktop.
Java 8+ CompletableFuture example with error handling
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;
});
@xytutu
Copy link

xytutu commented Dec 17, 2018

well done

@gaurav9822
Copy link

@mrsarm is it possible to throw the exception to the caller?

@mrsarm
Copy link
Author

mrsarm commented Oct 15, 2019

@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