Home > Back-end >  How to log empty Mono
How to log empty Mono

Time:01-01

Lets say I have the following lines

repository.findUser(name = "John Doe")
    .map {
        // User was found, continue processing
    }
    .switchIfEmpty(
        // Just log that the user was not found
    )

My non-best-practice-but-working approach currently is to just put the logging in another function and call it, like switchIfEmpty(userNotFound())

private fun userNotFound(): Mono<out Disposable> {
    logger.info { "No user was found." }
    return Mono.empty()
}

This works but I cannot imagine this is what I should be doing. How can I improve?

CodePudding user response:

One way is to use the Mono.defer inside switchIfEmpty:

repository.findUser(name = "John Doe")
    .switchIfEmpty(Mono.defer{ ... })

Alternatively, you could use doOnSuccess and check if Mono has completed without data(sample in Java):

repository.findUser(name = "John Doe")
    .doOnSuccess(e -> {
      if (e == null) { 
        log.info("No user was found.");
      }
    })
  • Related