1

I want to log an error to a mongo db collection and continue with the error propagation in the pipeline. How can I do that in project reactor?

Current code makes use of an extractor(Mono.block()), which to my knowledge, is not advised to use. This is what current code looks like:

        testMono.doOnError(throwable -> {
            var errorObject = ErrorObject.builder()
                    .message(throwable.getLocalizedMessage())
                    .className(throwable.getClass().getSimpleName())
                    .build();
            errorMessageRepository.save(errorObject).block();
        })

Is this correct way to do it or should I use a Mono.subscribe() here?

n0noob
  • 889
  • 8
  • 23

1 Answers1

0

You should avoid using block().

If you need a fire-and-forget call you could use subscribe():

 testMono.doOnError(throwable -> {
            var errorObject = ErrorObject.builder()
                    .message(throwable.getLocalizedMessage())
                    .className(throwable.getClass().getSimpleName())
                    .build();
            errorMessageRepository.save(errorObject).subscribe();
        })

Note that in that case, you lose backpressure support.

Alternatively, you could use onErrorResume operator like this:

testMono.onErrorResume(throwable -> {
    var errorObject = ErrorObject.builder()
            .message(throwable.getLocalizedMessage())
            .className(throwable.getClass().getSimpleName())
            .build();
    return errorMessageRepository.save(errorObject).then(Mono.error(throwable)));
});

That way, then operator replays the error as is.

lkatiforis
  • 5,703
  • 2
  • 16
  • 35
  • Just to confirm. Does this code propagates the same error in the pipeline after the save to db operation completion ? – n0noob Oct 29 '21 at 08:35
  • Yes, `then` operator replays the error as is. – lkatiforis Oct 29 '21 at 08:49
  • How could one loose back pressure support using the fire-and-forget method mentioned above? Could you please provide any article or document for me to read further on this? – n0noob Oct 29 '21 at 09:20
  • 1
    See https://stackoverflow.com/a/57569541/8909235 and https://stackoverflow.com/questions/57296097/how-does-backpressure-work-in-project-reactor – lkatiforis Oct 29 '21 at 09:22