spring-framework
spring-framework copied to clipboard
Functional style error fallback support in RestClient.retrieve()
The RestClient is great. However, its error handling design is currently limited to side effect style callbacks through .onStatus(...), where the typical behavior is to throw exceptions. 😬
In many cases, especially when writing resilient or fault-tolerant clients, developers would prefer to use functional style fallbacks, returning a default or cached value when the response status indicates an error, instead of throwing and catching exceptions manually. It helps us to write clean code.
Current Behavior
Book book;
try {
book = restClient.get()
.uri("/books/{id}", id)
.retrieve()
.body(Book.class);
} catch (RestClientException ex) {
book = defaultBook;
}
Proposed Enhancement Introduce a functional-style error fallback mechanism (similar to WebClient’s reactive operators).
Book book = restClient.get()
.uri("/books/{id}", id)
.retrieve()
.onStatus(HttpStatusCode::is5xxServerError, (req, res) -> defaultBook)
.body(Book.class);
Motivation
- Keeps the API consistent with the functional style of WebClient.
- Reduces boilerplate and improves readability for simple fallback cases.
- Encourages exception-free control flow for predictable errors like 404 or 500.