And*_*v93 3 java guava google-guava-cache
我正在尝试使用Google Guava缓存按服务相关对象进行缓存。在发生缓存未命中时,我使用我的REST客户端来获取对象。我知道我可以通过以下方式做到这一点:
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)
Run Code Online (Sandbox Code Playgroud)
现在,client.getKey(Key k)实际上抛出InternalServerException和ResourceNotFoundException。当我尝试使用此缓存实例获取对象时,可以将异常捕获为ExecutionException。
try {
cache.get(key);
} catch (ExecutionException e){
}
Run Code Online (Sandbox Code Playgroud)
但是,我想专门捕获并处理我定义的CacheLoader抛出的异常(即InternalServerException和ResourceNotFoundException)。
我不确定是否检查的实例是否ExecutionException是我自己的异常之一,是否会导致load()方法的签名实际上抛出Exception而不是ExecutionException。即使我可以使用instanceof,它也不是很干净。有解决这个问题的好方法吗?
从javadocs:
ExecutionException-如果在加载值时引发了检查异常。(即使计算被InterruptedException中断,也会抛出ExecutionException。)
UncheckedExecutionException-如果在加载值时引发了未经检查的异常
您需要通过调用getCause()检查捕获的ExecutionException的原因:
} catch (ExecutionException e){
if(e.getCause() instanceof InternalServerException) {
//handle internal server error
} else if(e.getCause() instanceof ResourceNotFoundException) {
//handle resource not found
}
}
Run Code Online (Sandbox Code Playgroud)