My previous 2 posts were about Springboot REST Client. This post will be a continuation on that topic. In this post, I will write about how we can handle error responses in the Springboot REST client.
Let’s go back to our previous example where we sent a POST request to an external server with some request parameters. This time we will handle 2 error cases. If the server sends a 4xx error response, we simply log “Client error” and then print the actual status code. If the server sends a 5xx error response, we log “Server error” and then print the status code.
public void sendPostWithParams(){
RestClient client = getRestClient();
MultiValueMap<String,String> params = new LinkedMultiValueMap();
params.add("api-key",SECRET_KEY);
params.add("product-type",productType);
ResponseDTO<Product[]> products = client.uri("/api/v1/products")
.body(params)
.retrieve()
.onStatus(HttpStatusCode::is4xxClientError,((req, res) -> {
log.error("Client error. Code: {}",res.getStatusCode());
}))
.onStatus(HttpStatusCode::is5xxClientError,((req, res) -> {
log.error("Server error. Code: {}",res.getStatusCode());
}))
.body(new ParameterizedTypeReference<ResponseDTO<Product[]>>() {});
}Notice, we are using the onStatus() method for handling the error. The onStatus() method has 2 implementation. One accepts a HttpStatusCode predicate and a ErrorHandler object. We showed this implementation in the example. The ErrorHandler object has HttpRequest and ClientHttpResponse parameters. We can access the response code through the getStatusCode() method of ClientHttpResponse.
The other implementation of onStatus() method accepts a ResponseErrorHandler object. The ResponseErrorHandler interface has several implementation. However, we can provide the DefaultResponseErrorHandler implementation. In this case, the internal handleError() method will be automatically called and an exception will occur based on error response status code.
public void sendPostWithParams(){
RestClient client = getRestClient();
MultiValueMap<String,String> params = new LinkedMultiValueMap();
params.add("api-key",SECRET_KEY);
params.add("product-type",productType);
ResponseDTO<Product[]> products = client.uri("/api/v1/products")
.body(params)
.retrieve()
.onStatus(new DefaultResponseErrorHandler())
.body(new ParameterizedTypeReference<ResponseDTO<Product[]>>() {});
}