How run logic when reactive repository return empty Mono?

Viewed 2121

I have interface like below to find Entity by phoneNumber in MongoDB:

public interface UserRepository extends ReactiveMongoRepository<User, String> {
    
    Mono<User> findByPhoneNumber(String phoneNumber);
}

This code is working and throw exception when Mono is empty, but I don't like it.

userRepository.findByPhoneNumber(PHONE_NUMBER)

    .switchIfEmpty(Mono.error(new IllegalArgumentException("user phone number not exist: " + PHONE_NUMBER)))
    .subscribe(result -> {

        // DO LOGIC HERE

    });

I would like to do something like this. I don't want to throwing exception, because it is normal that User Entity could be not found in MongoDB. I would like to to different logic when Mono is empty.

userRepository.findByPhoneNumber(PHONE_NUMBER)

    .switchIfEmpty(() -> {

        // DO OTHER LOGIC HERE when Mono is empty

    })
    .subscribe(result -> {

        // DO LOGIC HERE

    });

1 Answers

I think you could get a better code by using the Spring WebFlux Documentation Example

So instead of:

userRepository.findByPhoneNumber(PHONE_NUMBER)

    .switchIfEmpty(() -> {

        // DO OTHER LOGIC HERE when Mono is empty

    })
    .subscribe(result -> {

        // DO LOGIC HERE

    });

You would have something like

 public Mono<User> findByPhoneNumber(String phoneNumber) { 
        return repository.findByPhoneNumber(phoneNumber)
            .switchIfEmpty(Throw YOUR_EX());
    }

If you don't want to throw an Exception inside your switchIfEmpty, you could try returnin a Mono.Empty:

 public Mono<User> findByPhoneNumber(String phoneNumber) { 
        return repository.findByPhoneNumber(phoneNumber)
            .switchIfEmpty(Mono.defer(() -> {
               log.error("No Users found with phoneNumber [{}]", phoneNumber);
               return Mono.empty();
    }));
 }

Also you can get some detailed info here.

Related