Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catch External API Error Message as in Postman Body

I am using the following code to complete an External API call.

  WebResponse response = request.GetResponse();

  string JSONResult = null;
  var data = response.GetResponseStream();
  using (var reader = new StreamReader(data))
  {
    JSONResult = reader.ReadToEnd();
  }

When there is an exception on the external API, the request.GetResponse throws an error. However, I cannot get the message that is displayed, e.g.

{
        "Message": "No HTTP resource was found that matches the request URI '<site>/Foo'.",
        "MessageDetail": "No type was found that matches the controller named 'Foo'."
 }

Whilst this is displayed in Fiddler and Postman, I cannot get this message anywhere when it is thrown as an exception.

How do I get this specific details when an error on an external API's call is made?

like image 638
Peter PitLock Avatar asked Nov 16 '25 06:11

Peter PitLock


1 Answers

You need to catch the exception and then read the response stream of the exception. Reading the exception's response stream is the same as reading the response of the request. Here is how:

WebRequest request = 
WebRequest.Create("http://...");
WebResponse response = null; 
try
{
    response = request.GetResponse();
}
catch (WebException webEx)
{
    if (webEx.Response != null)
    {
        using (var errorResponse = (HttpWebResponse)webEx.Response)
        {
            using (var reader = new StreamReader(errorResponse.GetResponseStream()))
            {
                string error = reader.ReadToEnd();
                // TODO: use JSON.net to parse this string
            }
        }
    }
}

Do not put all your code inside the above try block because you are only try(ing) and catch(ing) the request.GetResponse(). The rest of your code needs to go outside that try catch block so you can catch the exceptions from that code separately.

like image 171
CodingYoshi Avatar answered Nov 18 '25 19:11

CodingYoshi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!