Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpWebRequest WebException ProtocolError

I'm trying to understand something about exception handling with a HttpWebRequest.

I have a client library and it's making a request to a WebAPI controller;

HttpWebRequest r = (HttpWebRequest)WebRequest.Create(url);

r.Method = "POST";
r.ContentType = "application/json";

foreach (var header in request.Headers)
{
     r.Headers.Add(header.Key, header.Value.ToString());
}

r.ContentLength = request.RequestBody.Length;

using (StreamWriter writer = new StreamWriter(r.GetRequestStream()))
    writer.Write(request.RequestBody);

I know the request will throw an exception, and contain the message entity already exists - 1234.

When I get the response;

using (HttpWebResponse response = (HttpWebResponse)r.GetResponse())
{
    if (response.StatusCode == HttpStatusCode.OK)
        using (StreamReader reader = new StreamReader(response.GetResponseStream()))
            return reader.ReadToEnd();

     return "Invalid"; 
 }

I get a WebException thrown. So, the caller of the request has a try..catch in it. And I get the WebException. What I get is a protocol error, not the 500 internal server error that was thrown (using correct status codes to represent the message comes later). Now if I read the Response of the WebException, it does contain my message and the stacktrace.

Questions

  • Why do I not get a status code of 500 in my response, why does it throw a protocol error?
  • Is there a more correct way of handling the request?

I have searched around and found some people getting this issue when not using the correct headers etc. But as far as I can tell, I have added all the headers that I can and still get the same behavior.

like image 666
tbddeveloper Avatar asked Sep 26 '14 15:09

tbddeveloper


People also ask

What is System Net WebException?

The WebException class is thrown by classes descended from WebRequest and WebResponse that implement pluggable protocols for accessing the Internet. When WebException is thrown by a descendant of the WebRequest class, the Response property provides the Internet response to the application.

What is HttpWebRequest C#?

The HttpWebRequest class provides support for the properties and methods defined in WebRequest and for additional properties and methods that enable the user to interact directly with servers using HTTP.


1 Answers

An 500 internal server error usually means that the API received the request but threw an unhandled exception while processing it, thus the "Internal Server Error".

You may log to a database or file all your API's unhandled exceptions to help your debugging process. Good luck.

like image 158
dialex Avatar answered Oct 15 '22 08:10

dialex