java / intermediate
Snippet
Resilient Fallbacks for Reactive HTTP Calls with WebClient and onErrorResume
When developing reactive microservices with Spring WebFlux, network calls can fail due to timeouts or remote HTTP error codes. The `onErrorResume` operator intercepts specific reactive stream exceptions and switches downstream consumers to a fallback `Mono` without crashing the entire subscriber pipeline or throwing unhandled errors.
snippet.java
java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public Mono<UserProfile> fetchUserProfileWithFallback(String userId) {return webClient.get().uri("/api/users/{id}", userId).retrieve().bodyToMono(UserProfile.class).timeout(Duration.ofMillis(1500)).onErrorResume(WebClientResponseException.NotFound.class, ex -> {log.warn("Remote profile not found for user: {}", userId);return Mono.just(UserProfile.anonymousDefault());}).onErrorResume(TimeoutException.class, ex -> {log.error("User service timed out, returning cached profile", ex);return cacheService.getCachedProfile(userId);});}
spring
Breakdown
1
.timeout(Duration.ofMillis(1500))
Emits a TimeoutException if the remote service does not emit a response within 1.5 seconds.
2
.onErrorResume(WebClientResponseException.NotFound.class, ex -> {
Selectively catches HTTP 404 response errors and defines a fallback publisher function.
3
return Mono.just(UserProfile.anonymousDefault());
Provides a safe default fallback value wrapped in a Mono instead of propagating the error.
4
.onErrorResume(TimeoutException.class, ex -> {
Handles timeout failures specifically by attempting to retrieve stale data from a local cache.