Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return the same status code from a second API call

I have an ASP.NET Core API calling a second API.

I throw an exception in my services layer, if there is an error from the second API:

var response = await httpClient.SendAsync(request); //call second API

if (!response.IsSuccessStatusCode)
{
    //return HTTP response with StatusCode = X, if response.StatusCode == X
    throw new HttpRequestException(await response.Content.ReadAsStringAsync()); 
    //this always returns 400
}

How can I throw an exception that will return a response with the same status code from the second API call?

If I use HttpRequestException it will always return 400, even if the response object had StatusCode = 500.

EDIT: The first API endpoint looks like this:

            public async Task<ActionResult<HttpResponseMessage>> CreateTenancy([FromBody]TenancyRequest tenancy)
            {
                //Make some calls...
                return Created(string.Empty, new { TenancyID = newTenancyExternalId });
            }

The second API endpoint looks like this:

    [HttpPost]
    public IHttpActionResult CreateTenancy([FromBody]TenancyDTO tenancyDTO)
    {    
        var tenancy = GetTenancy();    
        return Created(string.Empty, tenancy);
    }

I've tried using throw new HttpResponseException(response); but this removes the descriptive Exception message, the payload ends up like this:

{
    "Code": 500,
    "CorrelationId": "2df08016-e5e3-434a-9136-6824495ed907",
    "DateUtc": "2020-01-30T02:02:48.4428978Z",
    "ErrorMessage": "Processing of the HTTP request resulted in an exception. Please see the HTTP response returned by the 'Response' property of this exception for details.",
    "ErrorType": "InternalServerError"
}

I'd like to keep the ErrorMessage value in the original payload:

{
    "Code": 400,
    "CorrelationId": "ff9466b4-8c80-4dab-b5d7-9bba1355a567",
    "DateUtc": "2020-01-30T03:05:13.2397543Z",
    "ErrorMessage": "\"Specified cast is not valid.\"",
    "ErrorType": "BadRequest"
}

The end goal is to have this returned:

{
    "Code": 500,
    "CorrelationId": "ff9466b4-8c80-4dab-b5d7-9bba1355a567",
    "DateUtc": "2020-01-30T03:05:13.2397543Z",
    "ErrorMessage": "\"Specified cast is not valid.\"",
    "ErrorType": "InternalServerError"
}
like image 384
David Klempfner Avatar asked Oct 29 '25 00:10

David Klempfner


1 Answers

I tried something simple as changing the return type of the API endpoint and returning the object as it when there is an error. Otherwise, build your own HttpResponseMessage and return that. This snippet below uses text but you can use a serializer to serialize other content if you have.

public async Task<HttpResponseMessage> Test(string str)
{
    var httpClient = new HttpClient();
    var request = new HttpRequestMessage(HttpMethod.Get, $"myAPI that returns different errors 400, 404, 500 etc based on str");

    var response = await httpClient.SendAsync(request);
    if (!response.IsSuccessStatusCode)
        return response;

    // do something else
    return new HttpResponseMessage(System.Net.HttpStatusCode.OK) { Content = new StringContent("Your Text here") };
}

Other approach of using Filters

The other approach of using IHttpActionResult as your return type, you can use Filters to conform all your HttpResponseMessages to IHttpActionResult.

Filter: Create a separate cs file and use this filter definition.

public class CustomObjectResponse : IHttpActionResult
{
    private readonly object _obj;

    public CustomObjectResponse(object obj)
    {
        _obj = obj;
    }

    public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
    {
        HttpResponseMessage response = _obj as HttpResponseMessage;
        return Task.FromResult(response);
    }
}

and in your API, you would use your filter like so,

public async Task<IHttpActionResult> Test(string str)
{
    var httpClient = new HttpClient();
    var request = new HttpRequestMessage(HttpMethod.Get, $"http://localhost:4500/api/capacity/update-mnemonics/?mnemonic_to_update={str}");

    var response = await httpClient.SendAsync(request);
    if (!response.IsSuccessStatusCode)
        return new CustomObjectResponse(response);

    // Other Code here

    // Return Other objects 
    KeyValuePair<string, string> testClass = new KeyValuePair<string, string>("Sheldon", "Cooper" );
    return new OkWithObjectResult(testClass);

    // Or Return Standard HttpResponseMessage
    return Ok();

}
like image 66
Jawad Avatar answered Oct 31 '25 15:10

Jawad