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

如果 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 是否为空,我必须抛出异常。


有任何想法吗?


qq_笑_17
浏览 97回答 1
1回答

白猪掌柜的

我的下面的方法是假设findAsyncById方法 returns CompletableFuture<Optional<ChildDTO>>。所以你可以使用过滤器检查lastName是否为空,如果为空则抛出异常orElseThrowpublic CompletableFuture<ChildDTO> findChild(@NotEmpty String id) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return ChildRepository.findAsyncById(id)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .thenApply(optionalChild -> optionalChild&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .map(Child -> ObjectMapperUtils.map(Child, ChildDTO.class))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// If child last name is empty then return empty optional&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .filter(child->!child.getLastName())&nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// If optional is empty then throw exception&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .orElseThrow(CurrentDataNotFoundException::new))
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java