Sub topic 7
Handling error responses
This chapter assumes you can build a RestClient from the Spring Boot RestClient.Builder, send a GET request, and map the JSON body to a record. It also assumes you know the HTTP status code classes: 2xx success, 4xx client error, 5xx server error. Here you will see what RestClient does when a server answers with an error. You will also see how to turn specific statuses into your own exceptions, how to read the error body, and which failures never reach the status handlers at all.
What happens by default
When you call retrieve(), RestClient waits for the response status line and headers. If you then ask for the body with body() or toEntity(), it checks the status first. A 4xx or 5xx status causes an exception, and the body is not mapped to your type.
The exceptions form a small hierarchy. All of them extend RestClientException, which is unchecked.
| Exception | When it is thrown |
|---|---|
| `RestClientResponseException` | Base class for any response with an error status. Carries the status, headers and body bytes. |
| `HttpClientErrorException` | 4xx status. Subclass of `RestClientResponseException`. |
| `HttpServerErrorException` | 5xx status. Subclass of `RestClientResponseException`. |
| `HttpClientErrorException.NotFound` and similar | Subclasses for specific statuses such as 400, 401, 403, 404, 409 and 429. |
| `ResourceAccessException` | An I/O failure such as a refused connection or a timeout. There is no response. |
| `RestClientException` | Base class. Also thrown for problems such as a body that cannot be converted to the requested type. |
Two details matter in practice:
- The exceptions are unchecked, so the compiler does not force you to catch them.
- The default behavior only triggers when you read the response through
body(),toEntity()ortoBodilessEntity(). Just callingretrieve()sends the request but throws nothing until one of those methods runs.
Catching the default exceptions
The simplest approach is to catch RestClientResponseException around the call. It exposes the status and the raw body.
import org.springframework.web.client.RestClient;
import org.springframework.web.client.RestClientResponseException;
record Todo(long id, String title, boolean completed) {}
class TodoLookup {
private final RestClient restClient;
TodoLookup(RestClient restClient) {
this.restClient = restClient;
}
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. Its toString() includes the numeric code and the reason phrase when one is known, for example 404 NOT_FOUND. getResponseBodyAsString() decodes the body bytes as text. Use getResponseHeaders() when you need headers such as Retry-After.
If you want to treat one status differently, catch the specific subclass first:
import org.springframework.web.client.HttpClientErrorException;
Todo findOrNull(long id) {
try {
return restClient.get().uri("/todos/{id}", id).retrieve().body(Todo.class);
} catch (HttpClientErrorException.NotFound e) {
return null;
}
}Catching exceptions works, but it spreads status knowledge across your call sites. The next section moves that decision into the request itself.
Mapping statuses with onStatus
onStatus registers a handler on the retrieve() result. It 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. The handler normally throws an 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);
}The status predicate compares integer values here, which works with any HttpStatusCode, including codes that are not in the HttpStatus enum. A server can legally return a code such as 499 or 599, so comparing against enum constants with == can miss them.
Handlers are checked in the order you register them. The first handler whose predicate matches runs. If a handler returns normally without throwing, the response is treated as handled and the default error behavior is skipped for that status. Unless you have a reason to do that, make your handler throw.
Predicates for status families
HttpStatusCode has helper methods, so you can match whole families:
Todo findWithFamilies(long id) {
return restClient.get()
.uri("/todos/{id}", id)
.retrieve()
.onStatus(status -> status.value() == 404,
(request, response) -> {
throw new TodoNotFoundException(id);
})
.onStatus(HttpStatusCode::is4xxClientError,
(request, response) -> {
throw new IllegalArgumentException(
"Rejected by server: " + response.getStatusCode());
})
.onStatus(HttpStatusCode::is5xxServerError,
(request, response) -> {
throw new IllegalStateException(
"Server failed: " + response.getStatusCode());
})
.body(Todo.class);
}Because the 404 handler is registered first, a 404 produces TodoNotFoundException, not the generic 4xx exception. Put the narrow rules before the broad ones.
This example needs the import org.springframework.http.HttpStatusCode.
Reading the error body inside a handler
The handler receives a ClientHttpResponse. You can read its body as a stream. This is how you extract a message from the server's error JSON. The body can be read only once, so read it inside the handler and do not read it again afterwards.
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.HttpStatusCode;
record ApiError(String code, String message) {}
class ApiException extends RuntimeException {
private final int status;
ApiException(int status, String message) {
super(message);
this.status = status;
}
int status() {
return status;
}
}
class TodoGateway {
private final RestClient restClient;
private final ObjectMapper objectMapper;
TodoGateway(RestClient restClient, ObjectMapper objectMapper) {
this.restClient = restClient;
this.objectMapper = objectMapper;
}
Todo find(long id) {
return restClient.get()
.uri("/todos/{id}", id)
.retrieve()
.onStatus(HttpStatusCode::isError, (request, response) -> {
ApiError error = objectMapper.readValue(response.getBody(), ApiError.class);
throw new ApiException(response.getStatusCode().value(), error.message());
})
.body(Todo.class);
}
}HttpStatusCode::isError is true for both 4xx and 5xx. The handler's lambda is allowed to throw IOException, so readValue needs no try/catch. If the server returns an error body that is not JSON, for example an HTML page from a gateway, readValue throws a JsonProcessingException. That would hide the real status. Consider a fallback when you do not control the server.
Where the default handler sits
Your onStatus handlers run before the default one. A request's handlers are consulted first, then the builder's default status handlers, then the built-in behavior that throws HttpClientErrorException or HttpServerErrorException.
You can also register handlers on the builder so every request from that client shares them:
RestClient clientWithDefaults(RestClient.Builder builder) {
return builder
.baseUrl("https://api.example.com")
.defaultStatusHandler(HttpStatusCode::is5xxServerError,
(request, response) -> {
throw new IllegalStateException(
"Upstream failure: " + response.getStatusCode());
})
.build();
}Use builder-level handlers for rules that hold for the whole API, such as translating every 5xx into one exception type. Use request-level onStatus for rules tied to one operation, such as "404 means this todo does not exist".
The following diagram shows the order in which a response is evaluated.
Failures that never reach a status handler
Status handlers need a response. Some failures happen before one exists.
- Connection refused, DNS failure, connect timeout, read timeout. These surface as
ResourceAccessException, with the originalIOExceptionas the cause. NoonStatushandler runs, because there is no status. - A body that does not match the target type. A 200 response with JSON that cannot be mapped to your record throws a
RestClientException(typically from the message converter). The status was fine, so no status handler is involved. - An empty body.
body(Todo.class)returnsnullwhen the response has no content, for example after a 204. It does not throw. Guard againstnullwhere the API can legitimately return no body.
To handle connection problems, catch ResourceAccessException separately:
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 "server answered " + e.getStatusCode().value();
} catch (ResourceAccessException e) {
return "no response: " + e.getMessage();
}
}ResourceAccessException and RestClientResponseException are both subclasses of RestClientException, and neither extends the other, so their catch order does not matter. If you also catch the base RestClientException, put it last.
Choosing where to handle errors
| Approach | Good for | Cost |
|---|---|---|
| Catch `RestClientResponseException` at the call site | Quick scripts, one-off calls | Status logic is repeated at each call. |
| Request-level `onStatus` | Mapping one status to a domain exception for one operation | Each operation must repeat the handler. |
| Builder `defaultStatusHandler` | Rules that apply to the whole API | Applies to every request, so it can surprise someone reading a single call. |
| Catch `ResourceAccessException` | Retry or fallback on network failure | Needs separate code from status handling. |
A common layout is one gateway class per remote API. The gateway converts all remote failures into a small set of domain exceptions. The rest of the application never sees RestClient types.
Common mistakes
- Reading the error body twice. The response stream is consumed on the first read. Read it once in the handler and keep the result.
- Handler that returns without throwing. The default error is skipped, and
body()then tries to map an error body to your success type. This often fails with a confusing conversion error or returns a partly filled object. - Broad handler registered first. A 4xx handler placed before a 404 handler hides it. Order narrow to broad.
- Treating 404 as an error when it is a valid answer. If "not found" is a normal outcome, return
Optionalornullfrom a gateway method instead of letting an exception travel up. - Retrying every exception. A 400 or 404 will not succeed on retry. A
ResourceAccessExceptionor a 503 might.
Exercise
A client calls restClient.get().uri("/todos/{id}", 7).retrieve().onStatus(HttpStatusCode::is4xxClientError, (req, res) -> { throw new IllegalArgumentException("bad"); }).onStatus(status -> status.value() == 404, (req, res) -> { throw new TodoNotFoundException(7); }).body(Todo.class). The server returns 404. Which exception does the caller receive, and how would you change the code so the caller receives TodoNotFoundException?
Show answer
The caller receives IllegalArgumentException. Handlers run in registration order and the first matching one wins, and a 404 satisfies is4xxClientError. To get TodoNotFoundException, register the 404 handler before the 4xx handler.
Exercise
The server is stopped and your code calls retrieve().body(Todo.class). You added onStatus(HttpStatusCode::isError, ...) to the request. Does the handler run? Which exception do you catch?
Show answer
The handler does not run, because no response arrives and so there is no status. The call throws ResourceAccessException, caused by an IOException such as a connection refusal. Catch ResourceAccessException separately from RestClientResponseException.
Exercise
Write the body of a builder-level handler so that every 5xx response from the client becomes an IllegalStateException whose message includes the status code.
Show answer
Call .defaultStatusHandler(HttpStatusCode::is5xxServerError, (request, response) -> { throw new IllegalStateException("Upstream failure: " + response.getStatusCode()); }) on the RestClient.Builder before build().