1.) Specific Exceptions :
As per the specification of completableFuture.get(), it throws following exceptions.
Unchecked Exceptions
CancellationException – if this future was cancelled
Checked Exceptions
ExecutionException – if this future completed exceptionally
InterruptedException – if the current thread was interrupted while waiting
- However you've wrapped them in catch block with generic Exception which is not ideal as it would remove the clarity of actual exception that happened.
- So instead of enclosing with
Exception you should put the exception it can actually throw which is defined in contract.
try {
token = completableFuture.get();
} catch (InterruptedException | ExecutionException ex) {
logger.error("error getting token", ex);
}
Another extra : You can also wrap both the exceptions into your custom exception and rethrow from this catch block If you want this to be handled from the caller.
try {
token = completableFuture.get();
} catch (InterruptedException | ExecutionException ex) {
logger.error("error getting token", ex);
throw new TokenFetchException("error getting token", ex);
}
2.) Wrapping your token null logic.
You can easily include that logic in the try catch block but I would ask few questions to you.
- What is type of your
InternalErrorException class. An checked or unchecked exception ?
- If it is checked exception then either you'd need to add throws clause to this method or handle it inside catch clause.
- If it is unchecked exception, make sure you add the documentation to the method with
@throws.
What are the specific errors you getting when merging if else block inside try catch block ?
3.) Use optionals
Instead of throwing Exception in case of null, you can use Optional idioms introduced from Java8 onwards.
If token can be null then you can return Optional.empty() which makes your method's return type Optional<T>
Using Optional will depend on various invariants that you are currently adhering to. So it may or may not be possible to use it.
But try to incorporate that practice wherever if possible.
4.) Logging
when you're throwing this exception, No clear message will be printed as to what caused this. I might not be aware of internalError() method but you can include clear message as to why it failed in the exception somehow.
InternalErrorException.builder().internalError().build();
To capture a failure, the detail message of an exception should
contain the values of all parameters and fields that contributed to
the exception. In other words, the detail message of an exception
should capture the failure for subsequent analysis.
How to ...questions are off-topic because they indicate the code isn't working as expected. Stack Overflow requests minimal reproducible code, here on Code Review we want to see more code, such as complete functions or classes so that we can do a better job of helping you improve your code. \$\endgroup\$