亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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 關注
  • 187 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號