Reputation: 125
I have 2 API lets call them API1 and API2
API1 is a system API that extracts data from a database and returns a List of Strings as a result.
API2 extracts the information from API1 and returns the List of Strings as is.
Now my question is if API1 is down how do I handle it. I know I have to use a ResponseEntity to extract the HTTP status code but I am unable to do it. Conside the code below as an example
API1 service
private static List<String> getData(int attribute1){
//A piece of code that extracts data from the database based on the attribute1 and store the information in a res object<br>
return res;
}
API2 service
private static List<String> getData(int attribute1){
String uri="localhost:9191/getData/"+attribute1;
private RestTemplate restTemplate = new RestTemplate();
List<String> res = restTemplate.getForObject(uri, List.class);
return res;
}
Would I need to change my return type of API1 service functions
If so how would they look like
Irrespective of what happens in API1, API2 will change and how so to accomodate ResponseEntity
Any help would be much appreciated.
Upvotes: 0
Views: 942
Reputation: 571
In case your API1 is down or has any problems, you'll get an exception calling the "getForObject" method using RestTemplate. If you read the documentation, you'll see that this method throws a RestClientException, which means that if you want to handle any problem with API1 you need to try/catch the method and handle the exception accordingly with your needs. So, you'll have something like this:
private static List getData(int attribute1) {
String uri = "localhost:9191/getData/" + attribute1;
private RestTemplate restTemplate = new RestTemplate();
try {
List res = restTemplate.getForObject(uri, List.class);
return res;
} catch(RestClientException rce) {
// Here you'll handle the exception
}
}
Also, note that the RestClientException has 3 direct subclasses: ResourceAccessException, RestClientResponseException and UnknownContentTypeException. You could catch each one of these instead of cathing RestClientException, so you can handle them in different ways.
Upvotes: 2