为了账号安全,请及时绑定邮箱和手机立即绑定

java 使用可完成的 Future 发送异常

java 使用可完成的 Future 发送异常

qq_笑_17 2023-08-23 14:55:28
如果 CompletableFuture 代码中的字段为空,我必须发送异常: public CompletableFuture<ChildDTO> findChild(@NotEmpty String id) {            return ChildRepository.findAsyncById(id)                    .thenApply(optionalChild -> optionalChild                            .map(Child -> ObjectMapperUtils.map(Child, ChildDTO.class))                            .orElseThrow(CurrentDataNotFoundException::new)); }这个想法是,如果孩子的字段为空,在这种情况下,我必须抛出一个自定义异常,我不太确定如何实现这一点。我的想法是使用 thenAccept 方法并发送异常,如下所示:public CompletableFuture<ChildDTO> findChild(@NotEmpty String id) {                return ChildRepository.findAsyncById(id)                        .thenApply(optionalChild -> optionalChild                                .map(Child -> ObjectMapperUtils.map(Child, ChildDTO.class))                                .orElseThrow(CurrentDataNotFoundException::new))     }.thenAccept{            ........................     }   ObjectMapperUtils Code:    public static <S, D> D map(final S entityToMap, Class<D> expectedClass) {        return modelMapper.map(entityToMap, expectedClass);    }public class ChildDTO {    @NotEmpty    private String id;    @PassengerIdConstraint    private String ownerId;    @NotEmpty    private String firstName;    @NotEmpty    private String lastName;    private String nickName;    @ChildAgeConstraint    private Integer age;    @NotNull    private Gender gender;    @NotEmpty    private String language;我必须评估数据库中的lastName 是否为空,我必须抛出异常。有任何想法吗?
查看完整描述

1 回答

?
白猪掌柜的

TA贡献1893条经验 获得超10个赞

我的下面的方法是假设findAsyncById方法 returns CompletableFuture<Optional<ChildDTO>>。所以你可以使用过滤器检查lastName是否为空,如果为空则抛出异常orElseThrow


public CompletableFuture<ChildDTO> findChild(@NotEmpty String id) {

            return ChildRepository.findAsyncById(id)

                    .thenApply(optionalChild -> optionalChild

                            .map(Child -> ObjectMapperUtils.map(Child, ChildDTO.class))

                             // If child last name is empty then return empty optional

                            .filter(child->!child.getLastName())   

                             // If optional is empty then throw exception

                            .orElseThrow(CurrentDataNotFoundException::new))


查看完整回答
反对 回复 2023-08-23
  • 1 回答
  • 0 关注
  • 89 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信