Sobes.tech
Senior

What is the difference between onErrorResume and onErrorReturn?

sobes.tech AI

Answer from AI

onErrorResume and onErrorReturn are operators in reactive libraries (e.g., Project Reactor) that handle errors but work differently:

  • onErrorReturn returns a predefined value when an error occurs and terminates the stream. It's a simple way to replace an error with a specific value.

  • onErrorResume switches to another Publisher (stream) upon an error, which can be dynamically generated based on the error itself. It allows for more flexible error handling, such as executing alternative logic or making a request.

Example:

Mono<String> source = Mono.error(new RuntimeException("Error"));

// onErrorReturn returns a fixed value
source.onErrorReturn("Default value")
      .subscribe(System.out::println); // Outputs: Default value

// onErrorResume switches to another Mono
source.onErrorResume(e -> Mono.just("Alternative value"))
      .subscribe(System.out::println); // Outputs: Alternative value

Thus, onErrorReturn is simpler and more static, while onErrorResume is more flexible and allows for custom error handling logic.