0

I am making 2 API calls:

Response result1 = restTemplate.postForObject(api1url, data1, Response.class);

Response result2 = restTemplate.postForObject(api2url, data2, Response.class);

I am using @RestControllerAdvice to handle the error if any service is down (505 Unavailable)

So an API is down, I will receive 505 regardless which API it is which I will handle it in @RestControllerAdvice. But the problem is I don't know which API is down. I can use try-catch to solve this problem but since overall I am making many API calls this would clutter my code and also I want to ( as practically much I can) to use only RestControllerAdvice to handle all exceptions.

My goal is to use RestControllerAdvice to handle exceptions specific to each API when it is down

Is there a way? Thanks

1 Answers1

0

This might help!

  1. Create your own Exception class (Let's say ApiCallFailedException)
  2. Add members to the class such as HTTP_CODE, ERROR_MESSAGE, ERROR_CODE etc which might be helpful to identify information
  3. Throw this ApiCallFailedException if any of your API call failed

For e.g.

public void apiCallMethod(){
if(callToAPIOneFailed()){
throw new ApiCallFailedException(Http_code,"Message that One API Failed" , error_code);
}
} 

.. so on for other APIs

  1. In your @RestControllerAdvice annotated class , define the following

@ExceptionHandler(value= {ApiCallFailedException.class}) @ResponseStatus(value=HttpStatus.Internal_server_error)

public void handleApiCallExceptions(Exception ex)

{

// However you define return value or void , but this handler will catch your ApiCallFailed exception

}

Harsh
  • 812
  • 1
  • 10
  • 23