gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 20:39:54 26 4
gpt4 key购买 nike

我正在重构一些代码以使用 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com