我正在重构一些代码以使用 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.getUnchecked和 Why we deprecated Throwables.propagate .
关于java - Guava 缓存和保留检查的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8645965/