0

I have 2 microservices lets call them A and B. Every request and response from B needs to go through A which is then shown on the front end. Everything works fine for 2xx response codes but when I get any error response code such as 5xx itself, the calling of API B throws an exception and I am unable to retrieve the response code.

How do I get the error response code instead of exceptions?

ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.POST, request, String.class);

This is what I am using to make the call to API B from A.

1 Answers1

0

There are multiple other way, you can handle exception, You can try below

try {
    restTemplate.exchange(...);
} catch (HttpStatusCodeException exception) {
    int statusCode = exception.getStatusCode().value();
    ...
}

Explanation: whenever exception occurs, it will be caught and we can get statusCode from HttpStatusCodeException

click here to check multiple other way

RenceAbi
  • 522
  • 2
  • 11
  • 26
  • Thanks but it not working when connection is refused by the other microservice( in case if its down) – Bharat Kumar Shukla May 05 '22 at 10:32
  • check that exception gives `502` in the log, because `502` represents `connection refused` or you can catch using `ConnectException` in one another `catch` block. Note: While explaining problem, please be specific, so that you will get correct answer, your question is more general, So as per your question `HttpStatusCodeException` is the way you can handle – RenceAbi May 05 '22 at 11:42