Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

500 Internal Server Error when using HttpWebRequest, how can I get to the real error?

Tags:

http

I'm trying to improve the information provided in response to an error handled within an app.

This is the code:

Try
        httpRequestObj = HttpWebRequest.Create(strRequest)
        httpRequestObj.Method = "GET"
        httpRequestObj.UseDefaultCredentials = True
*       httpResponse = httpRequestObj.GetResponse
        Using reader As StreamReader = New StreamReader(httpResponse.GetResponseStream())
            strXML = reader.ReadToEnd()
        End Using
    Catch ex As WebException
        'do something with ex
    End Try

The webexception is thrown on the * line

Currently all I see in the Exception is "The remote server returned an error: (500) Internal Server Error". I've looked at the exception in debug but the info I need isn't there- I guess the response would need to be read in to see that info but it never gets that far.

If I take the request and paste it into my browser directly I can see the error details in XML format that is returned from the API I'm calling, info like:

<Error>
  <description>info I want to get to here</description> 
  <detail /> 
  <code>info I want to get to here</code> 
  <source /> 
  <category>info I want to get to here</category> 
  <file>info I want to get to here</file> 
  <line>info I want to get to here</line> 
  <pad /> 
</Error>

Is there any way I can change this code so that I can get past the 500 error and see the actual response, I'd like to be able to parse this xml to find out the real problem for the failure.

Note: the Exception does have an ex.Response (System.Net.HttpWebResponse), but I can't see the info I need in there, only a load of Header info.

like image 929
DannykPowell Avatar asked Dec 04 '09 16:12

DannykPowell


2 Answers

You can get the error response from the exception....

try
{
....
} catch(Exception e) {
   if (e is WebException && ((WebException)e).Status==WebExceptionStatus.ProtocolError)
   {
      WebResponse errResp = ((WebException)e).Response;
      using(Stream respStream = errResp.GetResponseStream())
      {
         // read the error response
      }
   }
}
like image 52
feroze Avatar answered Nov 23 '22 18:11

feroze


        System.Net.WebResponse response = null;
        try
        {
            response = wreq.GetResponse();
        }
        catch (WebException e)
        {
            if (e.Status == WebExceptionStatus.ProtocolError)
            {
                string error = new System.IO.StreamReader(e.Response.GetResponseStream()).ReadToEnd();
            }
        }
        catch (Exception e)
        {
        }

as simple as this, You will get entire response in the string error.

like image 42
RkHirpara Avatar answered Nov 23 '22 18:11

RkHirpara