本文介绍了Guava缓存并保留检查异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在重构一些代码以使用。

I'm refactoring some code to use guava Cache.

初始代码:

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

为了不破坏我需要保留任何抛出的异常的东西,没有包装。

In order not to break something I need to preserve any thrown exception as is, without wrapping it.

目前的解决方案似乎有些丑陋:

Current solution appears somewhat ugly:

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

有没有办法使它更好吗?

Is there any possible way to make it nicer?

推荐答案

刚刚写完问题开始思考用泛型的实用程序方法。
然后记得有关的。
是的,它已经在那里了! )

Just after writing the question started thinking about utility method powered with generics.Then remembered something about Throwables.And yes, it's already there! )

所以解决方案是:

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

非常好!

另请参见 。

这篇关于Guava缓存并保留检查异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 15:44