![](/img/trans.png)
[英]Using Google Guava CacheLoader for custom class as Key
[英]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-如果在加載值時引發了檢查異常。 (即使計算被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
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.