Video in progress
How do you handle 4xx and 5xx responses when calling an external API with RestClient?
By default RestClient throws HttpClientErrorException for 4xx and HttpServerErrorException for 5xx. With onStatus or the builder's defaultStatusHandler you turn them into your own exceptions; if you need full control, use exchange().
📖 Answer
@Component
class PaymentGateway {
private final RestClient client;
PaymentGateway(RestClient.Builder builder, @Value("${payments.url}") String url) {
this.client = builder.baseUrl(url)
.defaultStatusHandler(HttpStatusCode::is5xxServerError, (req, res) -> {
throw new PaymentProviderDownException(res.getStatusCode());
})
.build();
}
PaymentResult charge(ChargeRequest r) {
return client.post().uri("/charges")
.body(r)
.retrieve()
.onStatus(s -> s.value() == 402, (req, res) -> {
throw new InsufficientFundsException();
})
.body(PaymentResult.class);
}
}
onStatus applies only to this call, while defaultStatusHandler applies to every call made through this client. If both exist, the one on the call is checked first.
With exchange((req, res) -> ...) you read the status, headers and body yourself, and no exception is thrown automatically. That's convenient when the provider's error code comes in the response body and you need to decide based on it.
Things to watch in practice:
- don't pass an external service's 404 through as a 500 in your own API: turn it into a meaningful exception and map it to the right status in a
@RestControllerAdvice; - be careful when logging the error body, since it may contain a token or personal data;
- timeouts and connection failures aren't statuses: they come out as
ResourceAccessExceptionand are caught separately.
Sign up to mark studied questions and save your progress.