Ad

How To Log Empty Mono

- 1 answer

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?

Ad

Answer

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.");
      }
    })
Ad
source: stackoverflow.com
Ad