Sub topic 7
Handling error responses
This chapter assumes you can build a RestClient, send a GET request, and read a body with retrieve().body(...). It also assumes you know HTTP status code classes (4xx client errors, 5xx server errors).
What happens by default
When you call retrieve(), RestClient checks the response status. A 4xx or 5xx status does not return normally. It throws an exception that extends RestClientResponseException.
The two common subclasses are HttpClientErrorException for 4xx and HttpServerErrorException for 5xx. Both carry the status code, the response headers, and the response body.
A 2xx or 3xx status passes through, and body() maps the content as usual.
Catching the default exception
You can catch RestClientResponseException and inspect it. This works when you want one place to translate every failure.
import org.springframework.web.client.RestClientResponseException;
String describeFailure(long id) {
try {
restClient.get().uri("/todos/{id}", id).retrieve().body(Todo.class);
return "ok";
} catch (RestClientResponseException e) {
return e.getStatusCode() + ": " + e.getResponseBodyAsString();
}
}getStatusCode() returns an HttpStatusCode. getResponseBodyAsString() returns the error body as text, which is often a JSON problem description from the server.
Mapping a status to a domain exception
Callers of your service usually should not depend on HTTP details. Use onStatus to turn a specific status into your own exception.
import org.springframework.http.HttpStatus;
class TodoNotFoundException extends RuntimeException {
TodoNotFoundException(long id) {
super("Todo " + id + " not found");
}
}
Todo findOrThrow(long id) {
return restClient.get()
.uri("/todos/{id}", id)
.retrieve()
.onStatus(status -> status.value() == HttpStatus.NOT_FOUND.value(),
(request, response) -> {
throw new TodoNotFoundException(id);
})
.body(Todo.class);
}onStatus takes two arguments:
- A predicate that receives the
HttpStatusCodeand returns true when the handler should run. - A handler that receives the request and the response. It runs only for matching statuses.
The handler throws the exception itself. If it returns without throwing, RestClient continues with the next handler or with the default behavior.
Matching a whole class of statuses
You can match by class instead of one code. HttpStatusCode has the methods is4xxClientError() and is5xxServerError().
Todo findWithHandlers(long id) {
return restClient.get()
.uri("/todos/{id}", id)
.retrieve()
.onStatus(status -> status.value() == 404, (request, response) -> {
throw new TodoNotFoundException(id);
})
.onStatus(HttpStatusCode::is5xxServerError, (request, response) -> {
throw new IllegalStateException(
"Todo service failed with " + response.getStatusCode());
})
.body(Todo.class);
}Handlers run in the order you registered them, and the first one that matches and throws wins. Put specific statuses before broad classes.
Reading the error body
Inside a handler, response.getBody() gives an InputStream. Read it there, because the response is closed once the handler finishes.
import java.io.IOException;
import java.io.UncheckedIOException;
Todo findWithMessage(long id) {
return restClient.get()
.uri("/todos/{id}", id)
.retrieve()
.onStatus(HttpStatusCode::is4xxClientError, (request, response) -> {
String body;
try {
body = new String(response.getBody().readAllBytes());
} catch (IOException e) {
throw new UncheckedIOException(e);
}
throw new IllegalArgumentException(
"Rejected with " + response.getStatusCode() + ": " + body);
})
.body(Todo.class);
}Common errors
| Symptom | Cause | Fix |
|---|---|---|
| A 404 returns `null` or a record with default values | You assumed 404 is silent. Some clients behave that way, but `RestClient` throws. | Catch the exception or add an `onStatus` handler. |
| Your `onStatus` handler seems ignored | It returns without throwing, so the default handling still applies. | Throw from the handler. |
| The broad 4xx handler hides the 404 handler | The broad handler was registered first and threw first. | Register specific statuses first. |
| Reading the body later fails or is empty | The response stream is closed after the handler. | Read the body inside the handler. |
| Network failures are not caught by `RestClientResponseException` | A refused connection or timeout is not an HTTP response. | Also handle `ResourceAccessException`. |
Connection failures are different
A status code exists only if the server answered. If the connection is refused or a timeout expires, RestClient throws ResourceAccessException. It is not a RestClientResponseException, so catch it separately if you want to retry or fall back.
import org.springframework.web.client.ResourceAccessException;
String safeDescribe(long id) {
try {
restClient.get().uri("/todos/{id}", id).retrieve().body(Todo.class);
return "ok";
} catch (RestClientResponseException e) {
return "HTTP " + e.getStatusCode().value();
} catch (ResourceAccessException e) {
return "unreachable: " + e.getMessage();
}
}Exercise
A service calls an API with retrieve().body(Todo.class). The server answers 503, and the code catches only RestClientResponseException. Later the server is shut down completely and the same code starts failing with an uncaught exception. Which exception is thrown in each case, and why?
Show answer
For the 503, RestClient throws HttpServerErrorException, a subclass of RestClientResponseException, because the server returned an HTTP response with a 5xx status. When the server is down, no response exists, so RestClient throws ResourceAccessException, which is not a RestClientResponseException. You must catch ResourceAccessException separately.
Exercise
You register .onStatus(HttpStatusCode::is4xxClientError, ...) that throws IllegalArgumentException, and then .onStatus(status -> status.value() == 404, ...) that throws TodoNotFoundException. A 404 arrives. Which exception does the caller see, and how do you fix the order?
Show answer
The caller sees IllegalArgumentException, because the broad 4xx handler is registered first and throws first. Register the 404 handler before the 4xx handler.