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
500
in my response, why does it throw a protocol error?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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With