Guava cache and preserving checked exceptions

后端 未结 1 1004
半阙折子戏
半阙折子戏 2020-12-28 15:37

I\'m refactoring some code to use guava Cache.

Initial code:

public Post getPost(Integer key) throws SQLException, IOException {
    return PostsDB.f         


        
相关标签:
1条回答
  • 2020-12-28 16:29

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

    It may also be necessary to handle UncheckedExecutionException or even ExecutionError.

    So the solution is:

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

    Very nice!

    See also ThrowablesExplained, LoadingCache.getUnchecked and Why we deprecated Throwables.propagate.

    0 讨论(0)
提交回复
热议问题