java - Guava 缓存和保留检查的异常

标签 java caching exception-handling guava checked-exceptions

我正在重构一些代码以使用 guava Cache .

初始代码:

public Post getPost(Integer key) throws SQLException, IOException {
    return PostsDB.findPostByID(key);
}

为了不破坏某些东西,我需要按原样保留任何抛出的异常,而不是包装它。

当前的解决方案看起来有些难看:

public Post getPost(final Integer key) throws SQLException, IOException {
    try {
        return cache.get(key, new Callable<Post>() {
            @Override
            public Post call() throws Exception {
                return PostsDB.findPostByID(key);
            }
        });
    } catch (ExecutionException e) {
        Throwable cause = e.getCause();
        if (cause instanceof SQLException) {
            throw (SQLException) cause;
        } else if (cause instanceof IOException) {
            throw (IOException) cause;
        } else if (cause instanceof RuntimeException) {
            throw (RuntimeException) cause;
        } else if (cause instanceof Error) {
            throw (Error) cause;
        } else {
            throw new IllegalStateException(e);
        }
    }
}

有没有办法让它变得更好?

最佳答案

刚写完问题就开始考虑使用泛型驱动的实用方法。 然后想起了一些关于Throwables的事情. 是的,它已经在那里了! )

可能还需要处理UncheckedExecutionException or even ExecutionError .

所以解决办法是:

public Post getPost(final Integer key) throws SQLException, IOException {
    try {
        return cache.get(key, new Callable<Post>() {
            @Override
            public Post call() throws Exception {
                return PostsDB.findPostByID(key);
            }
        });
    } catch (ExecutionException e) {
        Throwables.propagateIfPossible(
            e.getCause(), SQLException.class, IOException.class);
        throw new IllegalStateException(e);
    } catch (UncheckedExecutionException e) {
        Throwables.throwIfUnchecked(e.getCause());
        throw new IllegalStateException(e);
    }
}

非常好!

另见 ThrowablesExplained , LoadingCache.getUncheckedWhy we deprecated Throwables.propagate .

关于java - Guava 缓存和保留检查的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8645965/

相关文章:

java - 是否可以将小部件存储在列表/数组中?

java - 405 遗留应用程序中的第一个 REST API 不允许使用方法

java - 为什么 inet :/0. 0.0.0 被解释为 inet :/0:0:0:0:0:0:0:0 by com. sun.net.httpserver.HttpServer?

.htaccess - 如何使用 htaccess 将 fontawesome 放入缓存中

asp.net - WCF 缓存与 Page.Cache

客户端或服务器上的 ASP.NET 缓存

c# - 捕获通用的非致命异常

java - 在具有表格的 excel(xlsx) 工作表中写入数据

java - 关于多个 'catch'的问题

php - 如何在 PHP 和 MongoDB 中正确捕获异常