简体   繁体   中英

Guava CacheLoader throw and catch custom exceptions

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(ie 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?

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
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM