20 Ağustos 2023 Pazar

SpringWebFlux Mono.onErrorResume metodu - Fallback Value

Giriş
Açıklaması şöyle
Project Reactor provides several operators to manage errors effectively within reactive streams:

1. onErrorResume and onErrorReturn: These operators allow you to provide fallback values or alternative streams in case of an error. This can help prevent the entire stream from failing and provide a more graceful degradation.
2. doOnError: This operator lets you execute specific actions when an error occurs, such as logging the error or cleaning up resources. It doesn't interfere with the error propagation itself.
3. retry and retryWhen: These operators enable you to automatically retry an operation a specified number of times or based on a certain condition. This can be helpful for transient errors.
Kısaca onErrorResume exception'ı loglar ve varsayılan bir sonuç döndürür

Örnek
Şöyle yaparız
public Mono<User> getUserById(String id) {
  return userRepository.findById(id)
    .onErrorResume(throwable -> {
      log.error("Error occurred while fetching user by id: {}", id, throwable);
      return Mono.just(new User("default", "Default User"));
    });
}
Örnek
Şöyle yaparız
webClient.get()
    .uri("/endpoint")
    .retrieve()
    .bodyToMono(String.class)
    .doOnError(e -> log.error("Error occurred", e))
    .onErrorResume(e -> Mono.just("Fallback value"));

Hiç yorum yok:

Yorum Gönder