gpt4 book ai didi

java - CompletableFuture then 异常后撰写

转载 作者:行者123 更新时间:2023-12-02 10:39:51 25 4
gpt4 key购买 nike

我陷入了 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);
}
});
}

最佳答案

您可以预先转换为保存状态。

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

关于java - CompletableFuture then 异常后撰写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52998110/

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