I have a Web API application in .NET Core 3.1. In a controller I have a GET action that must return a JSON object with a name and a description. In order to retrieve the correct description I need to call an external API (not implemented by myself and outside of my control). This is the code in the controller:
public async Task<ActionResult<Models.Result>> Get(string name)
{
try
{
var objectWrapper = await _clientService.GetObjectAsync(name.ToLowerInvariant());
//Other logic here....
return Ok(new Models.Result { Name = name, Description = objectWrapper.Description} );
}
catch (Exception ex)
{
_logger.LogError($"Failed to get object {name}: {ex}");
if (ex is ApiCallFailedException apiCallEx)
return StatusCode((int)apiCallEx.HttpStatusCode);
return BadRequest($"Failed to get object {name}");
}
}
The _clientService
is the service responsible for the call to the external API:
public async Task<ObjectDto> GetObjectAsync(string name)
{
var objectWrapper = new ObjectDto();
var request = new HttpRequestMessage(HttpMethod.Get, $"object/{name}/");
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
using (var response = await _client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead))
{
if (response.IsSuccessStatusCode)
{
objectWrapper = await response.Content.ReadAsAsync<ObjectDto>();
}
else
{
throw new ApiCallFailedException(response.StatusCode);
}
}
return objectWrapper;
}
Therefore, I created a custom exception class ApiCallFailedException
to handle not successful status codes returned by the external API in order to be able to catch it in my controller action.
In the controller action, in caso of not successful status codes from the external API, I decided to return the same status code.
My question is: is this approach correct to handle external API call failure?
Thank you!