Guava CacheLoader 抛出并捕获自定义异常
Guava CacheLoader throw and catch custom exceptions
我正在尝试使用 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)
现在,client.getKey(Key k)
实际上会抛出 InternalServerException
和 ResourceNotFoundException
。当我尝试使用此缓存实例获取对象时,我可以捕获异常 ExecutionException
.
try {
cache.get(key);
} catch (ExecutionException e){
}
但是,我想专门捕获并处理我定义的 CacheLoader 抛出的异常(即 InternalServerException
和 ResourceNotFoundException
)。
我不确定检查 ExecutionException
的实例是否是我自己的异常之一是否可行,因为 load() 方法的签名实际上抛出 Exception
而不是 ExecutionException
。即使我可以使用 instanceof
,它看起来也不是很干净。有什么好的方法可以解决这个问题吗?
来自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
您需要通过调用 getCause() 来检查捕获 ExecutionException 的原因:
} catch (ExecutionException e){
if(e.getCause() instanceof InternalServerException) {
//handle internal server error
} else if(e.getCause() instanceof ResourceNotFoundException) {
//handle resource not found
}
}
我正在尝试使用 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)
现在,client.getKey(Key k)
实际上会抛出 InternalServerException
和 ResourceNotFoundException
。当我尝试使用此缓存实例获取对象时,我可以捕获异常 ExecutionException
.
try {
cache.get(key);
} catch (ExecutionException e){
}
但是,我想专门捕获并处理我定义的 CacheLoader 抛出的异常(即 InternalServerException
和 ResourceNotFoundException
)。
我不确定检查 ExecutionException
的实例是否是我自己的异常之一是否可行,因为 load() 方法的签名实际上抛出 Exception
而不是 ExecutionException
。即使我可以使用 instanceof
,它看起来也不是很干净。有什么好的方法可以解决这个问题吗?
来自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
您需要通过调用 getCause() 来检查捕获 ExecutionException 的原因:
} catch (ExecutionException e){
if(e.getCause() instanceof InternalServerException) {
//handle internal server error
} else if(e.getCause() instanceof ResourceNotFoundException) {
//handle resource not found
}
}