Guava 缓存并保留已检查的异常

发布于 2024-12-23 01:50:24 字数 1169 浏览 2 评论 0原文

我正在重构一些代码以使用番石榴缓存

初始代码:

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

有什么可能的方法让它变得更好吗?

I'm refactoring some code to use guava Cache.

Initial code:

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

淡水深流 2024-12-30 01:50:24

写完问题后,我开始思考由泛型驱动的实用方法。
然后想起了一些关于 Throwables
是的,它已经在那里了! )

可能还需要处理 UncheckedExecutionException 甚至 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);
    }
}

非常好!

另请参阅ThrowablesExplainedLoadingCache.getUnchecked 为什么我们弃用 Throwables.propagate

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.

淡淡離愁欲言轉身 2024-12-30 01:50:24

只需使用 Lombok 中的 @SneakyThrows 即可。
强制异常包装不再有问题。

<咆哮>
到了 2021 年,Java 仍然有检查异常……人们什么时候才能意识到,即使检查异常在纸面上看起来不错,但在实践中它们会造成太多问题?

长期解决方案:如果有机会,请转向合适的语言,例如 Kotlin。

Just use @SneakyThrows from Lombok.
No problem anymore with forced exception wrapping.

<rant>
It's 2021 and Java still has checked exceptions... When will people get it that, even if checked exceptions look good on paper, they create way too many problems in practice?

Long term solution: move to a proper language, like Kotlin, if you have the opportunity.
</rant>

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文