Here’s the code I am trying to refactor. The same Http client is being used in each nested try with resource. I don’t understand the rationale behind nesting client.execute() calls.
The code tries to Post data to an endpoint if resource is missing and retries to Post to a backup endpoint if earlier call fails
public void makeSeveralApiCalls() throws Exception {
try (final CloseableHttpClient client = HttpClients.createDefault()) {
try (final CloseableHttpResponse response = client.execute(httpGetUri())){
if (response.getStatusLine().getStatusCode() == 404) {
// Resource not found, Post data to Microservice A
try (final CloseableHttpResponse nestedResponse = client.execute(httpPostToMicroserviceA())) {
if (resp.getStatusLine().getStatusCode() == 201) {
LOGGER.info("Success");
} else {
// Microservice A could not consume data, log error response
final String responseString = EntityUtils.toString(resp.getEntity());
LOGGER.debug("Error response: " + responseString);
// Try to Post to Microservice B
try (final CloseableHttpResponse subResponse = client.execute(httpPostToMicroserviceB())) {
if (resp.getStatusLine().getStatusCode() == 201) {
LOGGER.info("Success");
} else {
// Is this exception propagated to the caller?
throw new RuntimeException("Very bad unrecoverable state");
}
}
}
}
}
}
Is this a valid way to call multiple executes on the same http client in a nested fashion. Is it better to separate out each client.execute() call?