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
});