rasilvap
rasilvap

Reputation: 2149

java Send exception with completable Future

I have to send an exception if a field is empty in a CompletableFuture code:

 public CompletableFuture<ChildDTO> findChild(@NotEmpty String id) {
            return ChildRepository.findAsyncById(id)
                    .thenApply(optionalChild -> optionalChild
                            .map(Child -> ObjectMapperUtils.map(Child, ChildDTO.class))
                            .orElseThrow(CurrentDataNotFoundException::new));
 }

The idea is if the child have a field empty in this case lastName, I have to throw a custom exception, I am not pretty sure how can I achieve this.

My idea is to use the thenAccept method and send the exception just like this:

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;

I have to evaluate if lastName is empty from the db I have to throw an exception.

Any ideas?

Upvotes: 1

Views: 323

Answers (1)

Ryuzaki L
Ryuzaki L

Reputation: 40048

My below approach is by assuming findAsyncById method returns CompletableFuture<Optional<ChildDTO>>. so you can use the filter to check lastName is empty or not, if empty throw exception using 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))

Upvotes: 1

Related Questions