Access Error Data from HTTP Response When HttpWebRequest Throws an Exception

This blog post explains how to access the response body that may contain error messages when an HTTP request returns an error. You can use this technique to diagnose HTTP service API calls that return errors and raise exceptions.

The following raise an WebException or an AggregateException if the HTTP request returns an error.

string url = "//TODO: insert URL";
HttpWebRequest = new HttpWebRequest(url);

using (Stream responseStream = ((HttpWebResponse)
  request.GetResponseAsync().Result).GetResponseStream())
{
  return new StreamReader(responseStream).ReadToEnd();
}

The AggregateException may wrap a WebException. If there is a WebException, it contains a WebResponse that may contain a stream of the HTTP response body that may contain error messages or other useful information. The following code demonstrates how to check for such a response body.

try
{
  using (Stream responseStream = ((HttpWebResponse)
    request.GetResponseAsync().Result).GetResponseStream())
  {
    return new StreamReader(responseStream).ReadToEnd();
  }
}
catch(AggregateException ex)
{
  if (ex.InnerException != null)
  {
    WebException wex = ex.InnerException as WebException;

    if (wex != null)
    {
      using (var stream = wex.Response.GetResponseStream())
      {
        using (var reader = new StreamReader(stream))
        {
          Console.WriteLine(reader.ReadToEnd());
        }
      }
    }
  }

  throw;
}
catch(WebException ex)
{
    using (var stream = ex.Response.GetResponseStream())
    {
        using (var reader = new StreamReader(stream))
        {
            Console.WriteLine(reader.ReadToEnd());
        }
    }

    throw;
}
catch (Exception ex)
{
    Console.WriteLine(ex.GetType() + " : " + ex.Message);
    throw;
}

Great. Now I know what I already knew from the context of my call.

 {"error_message":"Please send a valid multipart/form-data payload"}  

2 thoughts on “Access Error Data from HTTP Response When HttpWebRequest Throws an Exception

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: