For some strange reason, the "User not found" log gets outputted twice in the logs of my application, despite calling findUserById only once. I am not sure what causes this problem.
Is there a better way to approach this (logging and throwing an exception)?
Please note that the findById
call is of an API.
Edit:
It appears that the exception is thrown only once. Also, if I replace Mono.error
with Mono.defer
, the log is printed twice as well.
public Mono<User> getUser(String id) {
Mono<User> thisIsEmpty = getNoUser(); // Assume that this is empty
return Mono.defer(() -> thisIsEmpty.switchIfEmpty(Mono.defer(() -> findUserById(id))));
}
public Mono<User> findUserById(String id) {
log.info("This is printed once.");
Mono<User> user = repository.findById(id).switchIfEmpty(Mono.error(() -> { // findById is an API call of a library I use
log.error("User not found (this is printed twice)"); // Gets printed twice
throw new UserException(MY_ERROR_CODE, 401);
}));
user.subscribe(User -> ... // Do something if it is not empty
return user;
}