7
votes

I am attempting to use the Google Guava Cache to cache by service related objects. On cache miss, I use my REST client to fetch the object. I know that I can do this in the following way:

CacheLoader<Key, Graph> loader = new CacheLoader<Key, Graph>() {
     public Graph load(Key key) throws InternalServerException, ResourceNotFoundException {
       return client.get(key);
     }
   };
   LoadingCache<Key, Graph> cache = CacheBuilder.newBuilder().build(loader)

Now, client.getKey(Key k) actually throws InternalServerException and ResourceNotFoundException. When I attempt to use this cache instance to get the object, I can catch the exception as ExecutionException.

try {
  cache.get(key);
} catch (ExecutionException e){

}

But, I would like to specifically catch and handle the exceptions that the CacheLoader I have defined is throwing(i.e. InternalServerException and ResourceNotFoundException).

I'm not sure if checking whether the instance of ExecutionException is one of my own exceptions would work either, cause the signature of load() method actually throws Exception and not ExecutionException. Even if I could use instanceof, it doesn't seem very clean. Are there any good appraoches for addressing this?

1

1 Answers

9
votes

From javadocs:

ExecutionException - if a checked exception was thrown while loading the value. (ExecutionException is thrown even if computation was interrupted by an InterruptedException.)

UncheckedExecutionException - if an unchecked exception was thrown while loading the value

You need to check cause of caught ExecutionException by calling getCause():

} catch (ExecutionException e){
    if(e.getCause() instanceof InternalServerException) {
        //handle internal server error
    } else if(e.getCause() instanceof ResourceNotFoundException) {
        //handle resource not found
    }
}