Let us say I have two GET APIs in a Spring Boot application:
@RestController
@RequestMapping("/api")
public class Controller {
@GetMapping("/greet")
public String greet() {
System.out.println("greet called");
if (Math.random() > 0.2) {
throw new RuntimeException("Custom error");
}
return "Hello, this is your Spring Boot endpoint!";
}
@GetMapping("/testing")
public String testing() {
return WebClient.builder()
.baseUrl("http://localhost:8082").build().get().uri("/api/greet").retrieve()
.bodyToMono(String.class)
.retryWhen(Retry.backoff(1, Duration.ofSeconds(10))).block();
}
}
When I call the "greet" API (http://localhost:8082/api/greet), it correctly throws a RuntimeException with the message "Custom error" which is expected.
However, when I call the "testing" API (http://localhost:8082/api/testing), it throws a RetryExhaustedException.
I understand that the RetryExhaustedException is thrown when retries are exhausted. but I want the original API exception (RuntimeException("Custom error")) to be returned when calling the "testing" API.
How can I modify my code to achieve this?
I have tried to use onRetryExhaustedThrow and updated the Webclient code
@GetMapping("/testing")
public String testing() {
return WebClient.builder()
.baseUrl("http://localhost:8082").build().get().uri("/api/greet").retrieve()
.bodyToMono(String.class)
.retryWhen(Retry.backoff(1, Duration.ofSeconds(10))
.onRetryExhaustedThrow((retryBackoffSpec, retrySignal) -> retrySignal.failure()))
.block();
}
and then I call test API http://localhost:8082/api/testing but it not throws a RuntimeException with the message "Custom error"


