我正在嘗試使用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
,它看起來並不很乾淨。有沒有什麼好的解決方案呢?