Sobes.tech
Senior

How to handle exceptions in reactive code?

sobes.tech AI

Answer from AI

In reactive programming (for example, using Project Reactor or RxJava), error handling differs from the traditional approach. Instead of try-catch, a special operator is used to handle errors in the data stream.

Main error handling methods:

  • onErrorReturn — returns a fallback value when an error occurs.
  • onErrorResume — switches to another stream upon an error.
  • retry — repeats the subscription a specified number of times upon an error.
  • doOnError — allows performing side effects when an error occurs (logging, etc.).

Example in Reactor:

Flux.just(1, 2, 0, 4)
    .map(i -> 10 / i) // ArithmeticException when i=0
    .onErrorResume(e -> Flux.just(-1)) // return a stream with -1 on error
    .subscribe(System.out::println);

Thus, errors are not thrown outward but are handled within the reactive stream, which allows maintaining asynchrony and continuous data processing.

How to handle exceptions in reactive code? — Java - sobes.tech