Sub topic 9
Handling error responses
This chapter assumes you can write an @HttpExchange interface, build it with HttpServiceProxyFactory over a RestClient, and register it as a bean. It also assumes you know HTTP status code classes (2xx, 4xx, 5xx).
What happens by default
A declarative client delegates every call to the RestClient underneath it. By default, RestClient treats any 4xx or 5xx response as an error. It throws an exception, and the proxy method never returns a value.
- A 4xx response throws a subclass of
HttpClientErrorException, such asHttpClientErrorException.NotFoundfor 404. - A 5xx response throws a subclass of
HttpServerErrorException, such asHttpServerErrorException.ServiceUnavailablefor 503. - Both extend
RestClientResponseException. It gives yougetStatusCode(),getResponseHeaders(), andgetResponseBodyAsString().
Connection failures are different. If the server cannot be reached, you get a ResourceAccessException, because no HTTP status exists.
Catching exceptions at the call site
The simplest approach is to catch the specific exception where you can act on it.
import org.springframework.stereotype.Service;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.HttpServerErrorException;
@Service
class TodoService {
private final TodoClient todoClient;
TodoService(TodoClient todoClient) {
this.todoClient = todoClient;
}
Todo findOrNull(long id) {
try {
return todoClient.getTodo(id);
} catch (HttpClientErrorException.NotFound e) {
return null;
} catch (HttpServerErrorException e) {
throw new IllegalStateException(
"Todo service failed with " + e.getStatusCode(), e);
}
}
}Catch the narrowest type you can handle. A broad catch (Exception e) also swallows programming errors, such as a failed JSON conversion.
Returning the response instead of throwing
If you want to inspect the status yourself, you can declare ResponseEntity<T> as the return type. This does not turn off exceptions by itself. The default handler still throws for 4xx and 5xx. To get a ResponseEntity for error statuses, you must change the status handling on the client, as shown next.
Custom status handlers
You can replace the default behavior when you build the RestClient. The defaultStatusHandler method takes a predicate on the status code and a handler that receives the request and response.
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatusCode;
import org.springframework.web.client.RestClient;
import org.springframework.web.client.support.RestClientAdapter;
import org.springframework.web.service.invoker.HttpServiceProxyFactory;
class TodoNotFoundException extends RuntimeException {
TodoNotFoundException(String message) {
super(message);
}
}
@Configuration
class TodoClientConfig {
@Bean
TodoClient todoClient(RestClient.Builder builder) {
RestClient restClient = builder
.baseUrl("https://jsonplaceholder.typicode.com")
.defaultStatusHandler(
status -> status.value() == 404,
(request, response) -> {
throw new TodoNotFoundException(
"Not found: " + request.getURI());
})
.build();
return HttpServiceProxyFactory
.builderFor(RestClientAdapter.create(restClient))
.build()
.createClient(TodoClient.class);
}
}Now callers see a domain exception instead of an HTTP library type. This keeps RestClient details out of your service layer. Handlers you register run before the built-in default, so the 404 above is handled by your code, and other error statuses still throw the standard exceptions.
If you want errors to come back as a ResponseEntity without exceptions, register a handler that does nothing for the statuses you care about:
RestClient restClient = builder
.defaultStatusHandler(HttpStatusCode::is4xxClientError,
(request, response) -> { })
.build();With this, a method returning ResponseEntity<Todo> gets the 4xx status and headers. The body may not convert to Todo, since an error body usually has a different shape.
Common errors
| Symptom | Likely cause |
|---|---|
| `catch` block for a 404 never runs | A custom status handler already converted it to another exception |
| `ResponseEntity` return still throws on 404 | The default handler is active. Add a status handler |
| Conversion error on an error response | The error body does not match the declared return type |
| `ResourceAccessException` instead of a status exception | Network failure or timeout, not an HTTP error |
Exercise
A method is declared as ResponseEntity<Todo> getTodo(@PathVariable long id). The server returns 404 and you have not customized the client. What does the caller get, and how would you change that so the caller receives the 404 status in a ResponseEntity?
Show answer
The caller gets an HttpClientErrorException.NotFound thrown, because the default status handling throws for 4xx even when the return type is ResponseEntity. To receive the status instead, register a status handler on the RestClient.Builder with defaultStatusHandler(HttpStatusCode::is4xxClientError, (request, response) -> { }), which suppresses the exception for 4xx responses.