2017-02-08 34 views
2

我正在尝试使用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)居然抛出InternalServerExceptionResourceNotFoundException。当我尝试使用此缓存实例来获取对象时,我可以捕获异常为ExecutionException

try { 
    cache.get(key); 
} catch (ExecutionException e){ 

} 

但是,我想专门捕获和处理,我已经定义缓存加载抛出(即。InternalServerExceptionResourceNotFoundException)例外。

我不知道如果检查ExecutionException的实例是否是我自己的一个例外也会起作用,导致load()方法的签名实际上抛出Exception而不是ExecutionException。即使我可以使用instanceof,它看起来并不很干净。有没有什么好的解决方案呢?

回答

2

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 
    } 
}