我正在尝试使用Google Guava Cache来缓存与服务相关的对象。在缓存未命中时,我使用我的REST客户端来获取对象。我知道我可以通过以下方式做到这一点:Guava CacheLoader抛出并捕获自定义异常
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)
现在,client.getKey(Key k)
居然抛出InternalServerException
和ResourceNotFoundException
。当我尝试使用此缓存实例来获取对象时,我可以捕获异常为ExecutionException
。
try {
cache.get(key);
} catch (ExecutionException e){
}
但是,我想专门捕获和处理,我已经定义缓存加载抛出(即。InternalServerException
和ResourceNotFoundException
)例外。
我不知道如果检查ExecutionException
的实例是否是我自己的一个例外也会起作用,导致load()方法的签名实际上抛出Exception
而不是ExecutionException
。即使我可以使用instanceof
,它看起来并不很干净。有没有什么好的解决方案呢?