How to safely unwrap a CompletableException

1.9k views Asked by At

I'm trying to figure out a way in which when working with CompletableFuture to safely and without repeating the same code throughout my codebase, handle the CompletionException thrown when calling CompletableFuture.join().

The behavior I'm looking for is - If the cause of the exception is any unchecked exception, then it should be thrown as-is. If the cause is checked, then wrap it in some form of RuntimeException (I've used the base RuntimeException class for this example, but in a real application I'd use a custom derived class) and throw the wrapper exception.

So far, I've come up with the following utility function to do the unwrapping:

public static RuntimeException unwrapCompletionException(CompletionException e) {
    Throwable cause =  e.getCause();
    if (cause instanceof RuntimeException) {
        return (RuntimeException) cause;
    } else if (cause instanceof InterruptedException) {
        Thread.currentThread().interrupt();
        return new RuntimeException(e.getCause());
    } else {
        // Any other checked exception
        return new RuntimeException(e.getCause());
    }
}

And for example, the utility function could be used as so:

try {
    completableFuture.join();
} catch (CompletionException e) {
    throw unwrapCompletionException(e);
} catch (CancellationException e) {
    // Handled separately...
}

My question is about the safety of this approach and the completeness of the unwrapping code. Like for example, InterruptedException was one special case I could think of to handle, but maybe others exist as well. Maybe there are other consequences I didn't consider. Is my utility function missing anything in order to do what I'm intending when handling CompletionException in any circumstance?

0

There are 0 answers