- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试将存储库异常映射到服务异常。这样的做法好吗?
@Override
public CompletableFuture<Void> delete(String id, Map<String, String> headers) {
CompletableFuture<Void> future = repository.delete(id, headers);
return future.handle((aVoid, throwable) -> {
if (throwable != null) {
Throwable cause = throwable.getCause();
if (DbExcUtils.isFKViolation(throwable)) {
future.completeExceptionally(new BadRequestException(HAS_ASSIGNED_RECORDS_MESSAGE));
} else {
future.completeExceptionally(cause);
}
}
return aVoid;
});
}
最佳答案
方法handle
仅当目标 CompletableFuture
实例完成时才会调用其给定的 BiFunction
Returns a new
CompletionStage
that, when this stage completes either normally or exceptionally, is executed with this stage's result and exception as arguments to the supplied function.
从这个意义上说,你无法再次完成它。 completeExceptionally
的 javadoc州
If not already completed, causes invocations of
get()
and related methods to throw the given exception.
当 future 已经完成时,它本质上是一个空操作。
如果您只想映射异常类型,则使用 exceptionally
。
Returns a new
CompletionStage
that, when this stage completes exceptionally, is executed with this stage's exception as the argument to the supplied function. Otherwise, if this stage completes normally, then the returned stage also completes normally with the same value.
这似乎做了你正在尝试的事情,即。如果有则映射异常,否则返回结果。
例如,
return future.exceptionally(throwable -> {
Throwable cause = throwable.getCause();
if (DbExcUtils.isFKViolation(throwable)) {
throw new CompletionException(new BadRequestException(HAS_ASSIGNED_RECORDS_MESSAGE));
} else {
throw new CompletionException(cause);
}
});
请注意,我们正在抛出新的异常。
此外,您可能需要检查 throwable
是否为 CancellationException
(没有原因),并在执行映射逻辑之前重新抛出它。
您可以使用obtrudeException
,但我不推荐
Forcibly causes subsequent invocations of method
get()
and related methods to throw the given exception, whether or not already completed. This method is designed for use only in error recovery actions, and even in such situations may result in ongoing dependent completions using established versus overwritten outcomes.
关于java - CompleatableFuture在handle方法中可以异常完成吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61478904/
我是一名优秀的程序员,十分优秀!