In the previous parts we were trying to learn everything need to start the reactive programming. In this part we will try to explore how to handle error in Reactor. So, let’s start…
Suppose we need to do something when an error occurs by catching it from the try…catch block. The ideal case in regular programming is something that looks like the example below:
So how can we do something similar in reactive programming? There are many ways to do so. One of them is the onError callback of the subscribe() operator. The subscribe() operator takes an error callback as its 2nd parameter, like below:
try {
return callExternalService(k);
}
catch (RuntimeException error) {
//make a record of the error log("uh oh, falling back, service failed for key "+ k);
throw error;
}
We can do the similar thing using doOnError() operator. For example:
Marble diagram of onErrorComplete (Photo Credit: Project Reactor)
There can occur a situation when we are just concerned about the success and ignore the exception. And just want to complete the task, whatever success or error happens. Like:
Marble diagram of onErrorResume (Photo Credit: Project Reactor)
If you want more than a single default value and you have an alternative (safer) way of processing your data, you can use onErrorResume(). This would be the equivalent of “Catch and execute an alternative path with a fallback method.” For example, if your nominal process is fetching data from an external and unreliable service but you also keep a local cache of the same data that can be a bit more out of date but is more reliable, you could do the following:
Marble diagram of doFinally (Photo Credit: Project Reactor)
There always occurs a situation when we need to do something after a successful or error-handling operation. Traditionally we do so using the finally operator. For example:
As we saw, reactive programming is a very good programming paradigm that has a clean functional programming style called “operators” and gives a non-blocking, backpressure, and efficient way of programming. This is a very good choice for large-scale, high-traffic, and large-data applications. To work with reactive programming, we need to grow reactive thinking and a mindset. And we can achieve this thinking capability by deep diving into the details of reactive programming and gathering knowledge.
We use cookies and technologies like Google Analytics and
Microsoft Clarity to understand how users interact with our site
and improve your experience.