我被CompletableFuture异常处理困住了
我的逻辑是发送电子邮件并保存此操作的状态。如果发送电子邮件引发异常,则需要将状态与异常消息一起保存。
public interface MyService {
CompletableFuture<Boolean> sendEmail(String content, String address);
CompletableFuture<StatusResult> saveStatus(String content, String address);}
处理器类当前具有此代码。它可以正常工作,但对我来说却并不优雅。我们如何摆脱在阶段之间共享状态的错误局部字段?
@Component
public class Processor {
private static final Logger LOGGER = LoggerFactory.getLogger(Processor.class);
@Autowired
private MyService myService;
public CompletableFuture<StatusResult> sendEmail(String content, String address) {
AtomicReference<String> error = new AtomicReference<>();// just to forward error message from exception block to thenCompose
return myService.sendEmail(content, address).exceptionally(e -> {
LOGGER.error("Exception during send email ", e);
error.set(e.getMessage());
return null;
}).thenCompose(x -> {
if (x == null) {
return myService.saveStatus(error.get(), address);
} else {
return myService.saveStatus("good", address);
}
});
}
}
看起来像 handle 方法应该有所帮助,但它返回CompletableFuture的CompletableFuture
public CompletableFuture<StatusResult> sendEmail(String content, String address) {
CompletableFuture<CompletableFuture<StatusResult>> result = myService.sendEmail(content, address).handle((x, e) -> {
if (e != null) {
LOGGER.error("Exception during send email ", e);
return myService.saveStatus("error", address);
} else {
return myService.saveStatus("good", address);
}
});
}
答案 0 :(得分:2)
您可以预先转换为保存状态。
public CompletableFuture<String> sendEmail(String content, String address) {
return myService.sendEmail(content, address)
.thenApply(b -> "good")
.exceptionally(Throwable::getMessage)
.thenCompose(status -> myService.saveStatus(status, address));
}
答案 1 :(得分:-1)
另一种可行的解决方案:
ClientListView.getSelectionModel().getSelectedItems()