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?
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.