tbddeveloper
tbddeveloper

Reputation: 2447

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

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.

Upvotes: 9

Views: 9748

Answers (1)

dialex
dialex

Reputation: 2876

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.

Upvotes: 1

Related Questions