Sub topic 9
Handling error responses
A declarative client hides the HTTP call behind a Java method, but the remote service can still answer with a 404, a 500, or nothing at all. This chapter explains what your interface methods throw, how to turn those failures into exceptions your application understands, and how to test the failure paths.
This chapter assumes you have read the earlier chapters on @HttpExchange interfaces, RestClient, and HttpServiceProxyFactory. It also assumes you know HTTP status code classes (2xx, 4xx, 5xx) and how Java exceptions propagate.
Where errors are handled
An @HttpExchange interface has no error handling of its own. The generated proxy delegates each call to the RestClient you passed to RestClientAdapter. That RestClient decides what a 4xx or 5xx response means. Error handling is therefore configured on the RestClient.Builder, before you create the proxy.
What happens by default
With no extra configuration, RestClient uses a default status handler. It throws an unchecked exception for any 4xx or 5xx response. The exception types form a small hierarchy under RestClientResponseException.
| Situation | Exception thrown |
|---|---|
| Any 4xx response | `HttpClientErrorException` |
| A specific 4xx such as 404 or 400 | A nested subclass such as `HttpClientErrorException.NotFound` or `.BadRequest` |
| Any 5xx response | `HttpServerErrorException` |
| A status code that is not in the standard registry | `UnknownHttpStatusCodeException` |
| Connection refused, DNS failure, or timeout | `ResourceAccessException` |
Two points trip people up.
- A return type of
ResponseEntity<Todo>does not stop the exception. With the default handler, a 404 still throws, even thoughResponseEntitycan carry a status code. Do not writeif (response.getStatusCode().is4xxClientError())and expect it to run. ResourceAccessExceptionis not a response exception. No response arrived, so there is no status code or body to read. It wraps anIOException.
Catching the default exceptions
The simplest approach is to catch the nested subclasses where you call the client.
import org.springframework.stereotype.Service;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.ResourceAccessException;
@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 (ResourceAccessException e) {
throw new IllegalStateException("Todo API unreachable", e);
}
}
}Every response exception exposes the details of the failed call:
getStatusCode()returns theHttpStatusCode.getResponseHeaders()returns the headers.getResponseBodyAsString()returns the raw body.getResponseBodyAs(Class)converts the body with the configured message converters.
The last method is useful when the server returns a structured error, such as an RFC 9457 problem document:
import org.springframework.http.ProblemDetail;
import org.springframework.web.client.HttpClientErrorException;
class ProblemReader {
static String describe(HttpClientErrorException e) {
ProblemDetail problem = e.getResponseBodyAs(ProblemDetail.class);
return problem != null ? problem.getTitle() + ": " + problem.getDetail() : e.getMessage();
}
}getResponseBodyAs returns null when the body is empty. It can also fail if the body is not JSON, for example an HTML error page from a gateway. Check for that when the upstream might sit behind a proxy.
Custom status handlers
Catching Spring's exceptions in every caller couples your domain code to HTTP. A better design is to translate failures once, at the client boundary, into exceptions that belong to your application. Register status handlers on the builder with defaultStatusHandler.
A handler has two parts: a predicate on HttpStatusCode, and a function that receives the request and the response. The function usually throws.
import java.io.IOException;
import java.nio.charset.StandardCharsets;
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 uri) {
super("No todo at " + uri);
}
}
class TodoApiException extends RuntimeException {
private final int status;
TodoApiException(int status, String body) {
super("Todo API returned " + status + ": " + body);
this.status = status;
}
int status() {
return status;
}
}
@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(request.getURI().toString());
})
.defaultStatusHandler(HttpStatusCode::isError, (request, response) -> {
String body = new String(response.getBody().readAllBytes(), StandardCharsets.UTF_8);
throw new TodoApiException(response.getStatusCode().value(), body);
})
.build();
return HttpServiceProxyFactory
.builderFor(RestClientAdapter.create(restClient))
.build()
.createClient(TodoClient.class);
}
}Rules that matter when you write handlers:
- Order decides. Handlers are checked in the order you registered them, and the first match wins. Put the specific 404 handler before the general
isErrorone. If you reverse them, the 404 handler never runs. - Your handlers run before the built-in one. Responses that match none of your predicates still reach the default handler, so 4xx and 5xx responses you did not claim keep throwing the Spring exceptions.
- The callback may throw
IOException. Reading the body withgetBody()declares it, so you do not need a try block. Throw an unchecked exception, because the proxy method has nothrowsclause for checked ones. - A handler that returns normally lets the response through. Spring then converts the body as usual. If the body is an error document, conversion into
Todocan fail or produce an object full of nulls. Only return normally for statuses you really want to treat as success. - Read the body inside the handler. The response is closed after the call completes, so you cannot keep the stream for later.
The ResponseErrorHandler overload of defaultStatusHandler is also available. It suits you if you already have a handler written for RestTemplate.
Per-call handling is not available
On a plain RestClient call chain you can attach .onStatus(...) to a single request. An @HttpExchange method has no equivalent, because the proxy builds the call chain for you. All handlers on a client therefore apply to every method on that interface. If one endpoint needs different treatment from the rest, you have three options:
- Catch the default exception in the caller for that endpoint.
- Split the endpoint into its own interface and its own
RestClient. - Keep one handler that inspects
request.getURI()orrequest.getMethod()before choosing an exception.
The first option is usually enough.
Translating exceptions for your web layer
If your application is also a Spring MVC service, map your client exceptions to responses in one place.
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
class ClientErrorAdvice {
@ExceptionHandler(TodoNotFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
String notFound(TodoNotFoundException e) {
return e.getMessage();
}
@ExceptionHandler(TodoApiException.class)
@ResponseStatus(HttpStatus.BAD_GATEWAY)
String upstreamFailure(TodoApiException e) {
return "Upstream error " + e.status();
}
}Returning 502 Bad Gateway for an upstream failure tells your own callers that the fault is not in your service. Passing an upstream 500 straight through hides that.
Testing the failure paths
MockRestServiceServer can return any status, so error handling is easy to test without a network. Build the proxy from the same configured builder you use in production, so that your status handlers are active.
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo;
import static org.springframework.test.web.client.response.MockRestResponseCreators.withStatus;
import org.junit.jupiter.api.Test;
import org.springframework.http.HttpStatus;
import org.springframework.test.web.client.MockRestServiceServer;
import org.springframework.web.client.RestClient;
import org.springframework.web.client.support.RestClientAdapter;
import org.springframework.web.service.invoker.HttpServiceProxyFactory;
class TodoClientErrorTest {
@Test
void mapsNotFound() {
RestClient.Builder builder = RestClient.builder()
.baseUrl("http://localhost")
.defaultStatusHandler(status -> status.value() == 404, (request, response) -> {
throw new TodoNotFoundException(request.getURI().toString());
});
MockRestServiceServer server = MockRestServiceServer.bindTo(builder).build();
server.expect(requestTo("http://localhost/todos/99"))
.andRespond(withStatus(HttpStatus.NOT_FOUND));
TodoClient client = HttpServiceProxyFactory
.builderFor(RestClientAdapter.create(builder.build()))
.build()
.createClient(TodoClient.class);
assertThrows(TodoNotFoundException.class, () -> client.getTodo(99));
server.verify();
}
}If you duplicate the handler registration in the test, as above, you only test your copy. To test the real configuration, move the handler setup into a shared method that both the @Bean and the test call.
Common mistakes
- Relying on
ResponseEntityto avoid exceptions. The default handler still throws. Register a handler, or catch the exception. - Catching
Exceptionaround a client call. This also swallows your own bugs. CatchRestClientResponseExceptionfor HTTP errors andResourceAccessExceptionfor network failures. - Treating timeouts as HTTP errors. A timeout surfaces as
ResourceAccessException, not as a 504. The next chapter covers configuring them. - Putting a general handler first. A broad predicate such as
HttpStatusCode::isErrorregistered before a 404 handler hides it. - Leaking upstream bodies to users. Error bodies can contain internal details. Log them, and return your own message.
Exercise
A TodoClient method returns ResponseEntity<Todo>. The server answers 404, and you did not register any status handler. What does the caller receive, and how would you make the 404 produce a TodoNotFoundException instead?
Show answer
The caller receives no ResponseEntity. The default handler throws HttpClientErrorException.NotFound before the method returns. To get a TodoNotFoundException, register a handler on the RestClient.Builder before building the proxy: defaultStatusHandler(status -> status.value() == 404, (request, response) -> { throw new TodoNotFoundException(request.getURI().toString()); }). Register it before any broader isError handler, because the first matching handler wins.
Exercise
Why does a connection timeout not produce an HttpServerErrorException, and which exception should you catch for it?
Show answer
Status exceptions are created from a response, and a timeout means no response arrived. RestClient wraps the underlying IOException in ResourceAccessException, which has no status code or body. Catch ResourceAccessException for network-level failures.