Error Handling

Fallback

We can have fallback for our error. Considering these example

public static Mono<User> monoError() {  
  return Mono.error(new RuntimeException());  
}  
  
public static Flux<User> fluxError() {  
  return Flux.error(new RuntimeException());  
}

And

public static Mono<User> fallBackMonoFromError() {  
  return monoError().onErrorReturn(new User("default user"));  
}  
  
public static Flux<User> fallBackFluxFromError() {  
  return fluxError().onErrorResume(throwable -> Flux.just(
	  new User("default user"), 
	  new User("default user 2"))
  );  
}

onErrorReturn() will return the element for both Mono and Flux. Whereas onErrorResume() will allow us to create a new Flux therefore return multiple User

Exception handling

Considering the following method

private static User capitaliseUser(User user) throws Exception {  
  if (user.username.contains("default")) {  
    throw new Exception();  
  }  
  
  return new User(user.username.toUpperCase());  
}

When exception occured, we can use Reactor Exceptions.propagate to propagate the exception to a reactor class. For example:

public static void exceptionHandling() {  
  Flux<User> userFlux = Flux.just(  
      new User("austin"),  
      new User("hello"),  
      new User("default"),  
      new User("hi")  
  );  
  
  userFlux.mapNotNull(user -> {  
    try {  
      return capitaliseUser(user);  
    } catch (Exception e) {  
      throw Exceptions.propagate(e);  
    }  
  })  
  .onErrorContinue((throwable, affectedUser) -> System.out.println("Some error " + ((User) affectedUser).username))  
  .subscribe(user -> System.out.println(user.username));  
}

This will print out

AUSTIN
HELLO
Some error default
HI