Sub topic 3
Handling Error Responses in Declarative HTTP Clients
Assume Java 17, Spring Boot beans, HTTP status codes, and the HTTP interface created in the previous chapter.
Handling error responses
A RestClient-backed HTTP interface throws an HttpClientErrorException for a 4xx response and an HttpServerErrorException for a 5xx response. Catch specific exceptions when the caller can recover from a known status.
Todo findOrNull(long id) {
try {
return todoClient.getTodo(id);
} catch (HttpClientErrorException.NotFound ex) {
return null;
}
}For shared behavior, configure a status handler on the RestClient. Use it to map remote errors to application-specific exceptions. Do not silently ignore failures, because that can turn an outage into incorrect data.
Configuring timeouts
Timeouts belong to the underlying HTTP request factory. Configure both connection and response-read limits. The exact options depend on the HTTP client implementation.
HttpClient httpClient = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(2))
.build();
JdkClientHttpRequestFactory requestFactory =
new JdkClientHttpRequestFactory(httpClient);
requestFactory.setReadTimeout(Duration.ofSeconds(5));
RestClient restClient = RestClient.builder()
.requestFactory(requestFactory)
.baseUrl("https://api.example.com")
.build();Choose limits from the remote service’s normal response time and your application’s latency budget.
Testing without a network
MockRestServiceServer binds to a RestClient.Builder and returns canned responses.
MockRestServiceServer server = MockRestServiceServer.bindTo(builder).build();
server.expect(requestTo("http://localhost/todos/1"))
.andRespond(withStatus(HttpStatus.NOT_FOUND));
assertThrows(HttpClientErrorException.NotFound.class,
() -> client.getTodo(1));
server.verify();Registering clients by group
Spring Framework 7 and Spring Boot 4 support grouped registration:
@Configuration
@ImportHttpServices(group = "todos", types = TodoClient.class)
class HttpClientsConfig {}Configure the group’s base URL with:
spring.http.serviceclient.todos.base-url=https://api.example.comReactive clients with WebClient
Use WebClient and WebClientAdapter when calls must remain non-blocking. The interface can return Mono<T> or Flux<T>. Use RestClient for ordinary synchronous service code.
Choosing among alternatives
HTTP interfaces reduce repeated request code while keeping endpoints visible in Java. Choose direct RestClient calls when one-off customization is more important than a stable interface. Choose WebClient for reactive composition and streaming. Consider OpenFeign when its ecosystem or team conventions are already established.
Exercise
Which exception should a synchronous client usually catch for a missing resource?
Show answer
HttpClientErrorException.NotFound.