In spring project reactor, what are the differences between onErrorResume
and doOnError
? and when I should each of them ?
You may use a onErrorResume( ) which will return another stream on elements from the point you encountered that error. Note: Using the instanceOf method, you may be able to verify if its an Exception of some expected type and hence you could handle it accordingly.
onErrorResume
: Gives a fallback stream when some exception occurs happens in the upstream.
doOnError
: Side-effect operator. Suppose you want to log what error happens in the upstream.
Example:
Mono.just(request)
.flatMap(this::makeHTTPGet)
.doOnError(err -> {
log.error("Some error occurred while making the POST call",err)
})
.onErrorResume(err -> Mono.just(getFallbackResponse()));
You see, doOnError
is a side-effect operator. It's like inserting a thermometer into a water pipeline and reading the temperature. Does it affect the pipeline at all? No.
Suppose now that the pipeline breaks - the city still has to get water right? So we have a fallback pipeline that can be activate in such cases. onErrorResume
does exactly that.
Note: You could also log in onErrorResume
. Nothing stops you from doing that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With