【问题标题】:Guava CacheLoader throw and catch custom exceptionsGuava CacheLoader 抛出并捕获自定义异常
【发布时间】:2017-02-08 09:08:56
【问题描述】:

我正在尝试使用 Google Guava Cache 按服务相关对象进行缓存。在缓存未命中时,我使用我的 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) 实际上会抛出 InternalServerExceptionResourceNotFoundException。当我尝试使用此缓存实例获取对象时,我可以将异常捕获为ExecutionException

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

}

但是,我想专门捕获和处理我定义的 CacheLoader 抛出的异常(即InternalServerExceptionResourceNotFoundException)。

我不确定检查ExecutionException 的实例是否是我自己的异常之一是否会起作用,因为load() 方法的签名实际上会抛出Exception 而不是ExecutionException。即使我可以使用instanceof,它似乎也不是很干净。有什么好的方法来解决这个问题吗?

【问题讨论】:

    标签: java guava google-guava-cache


    【解决方案1】:

    来自javadocs

    ExecutionException - 如果在加载时抛出检查异常 价值。 (即使计算完成也会抛出 ExecutionException 被 InterruptedException 中断。)

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

    【讨论】:

      猜你喜欢
      • 2015-07-14
      • 2023-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-08
      • 1970-01-01
      相关资源
      最近更新 更多