3

I have to handle different exceptions in the Spring WebFlux chain. There is a WebClient and I need to have the logic, which would look like below code using the imperative style:

try {

} catch (WebClientResponseException e) {
   // flow 1
} catch (TimeoutException e) {
  // flow 2
} catch (Exception e) {
  // flow 3
}

The problem is that when building a reactive chain, I can only have one exception class or predicate:

...
.onErrorMap(WebClientResponseException.class, e -> {...})
.onErrorMap(Exception.class, e -> {...}) 
// will also be called for WebClientResponseException, which is not expected

Is it a common practice to use instanceof in these cases? Something like:

...
.onErrorMap(WebClientResponseException.class, e -> {...})
.onErrorMap(e -> !(e instanceof WebClientResponseException), e -> {...}) 
// will also be called for WebClientResponseException, which is not expected

OR

.onErrorMap(e -> {
   if (e instanceof WebClientResponseException) {
      // flow 1
   } else if (e instanceof TimeoutException) {
      // flow 2
   } else {
     // flow 3
   }
})

I believe in regular (non-reactive) java instanceof is considered to be a bad practice, however I do not see a better approach for the Reactive Stream.

Please share your thoughts

Rahul
  • 1,727
  • 3
  • 18
  • 33

0 Answers0