System.Net.WebException is not being caught
-
19-06-2021 - |
Вопрос
I have a strange issue happening. I have some code which must do an http post to a client's server. Their post returns content to me, which I need to show to my user. If thee is a problem, I want to trap the error and inject my own content to let the user know there was a problem.
Here is my static helper class for performing the http post.
public static class HttpPostHelper
{
public static string Post(string url, NameValueCollection values)
{
StringBuilder dataBuilder = new StringBuilder();
foreach (var key in values.AllKeys)
{
EncodeAndAddItem(ref dataBuilder, key, values[key]);
}
Uri uri = new Uri(url);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = dataBuilder.Length;
using (Stream writeStream = request.GetRequestStream())
{
UTF8Encoding encoding = new UTF8Encoding();
byte[] bytes = encoding.GetBytes(dataBuilder.ToString());
writeStream.Write(bytes, 0, bytes.Length);
}
string result = String.Empty;
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (Stream responseStream = response.GetResponseStream())
{
using (StreamReader readStream = new StreamReader(responseStream, Encoding.UTF8))
{
result = readStream.ReadToEnd();
}
}
}
return result;
}
private static void EncodeAndAddItem(ref StringBuilder baseRequest, string key, string dataItem)
{
if (baseRequest == null)
{
baseRequest = new StringBuilder();
}
if (baseRequest.Length != 0)
{
baseRequest.Append("&");
}
baseRequest.Append(key);
baseRequest.Append("=");
baseRequest.Append(System.Web.HttpUtility.UrlEncode(dataItem));
}
}
And here is my code that does the post and returns the content.
private string GetReturnContent(string callback, NameValueCollection data, LogRequest request)
{
string content = String.Empty;
try
{
content = HttpPostHelper.Post(callback, data);
request.Message = String.Format("Content Retrieved from Callback: {0}", content);
logService.Debug(request);
}
catch (System.Net.WebException ex)
{
var response = ex.Response as HttpWebResponse;
if (response != null)
{
if ((int)response.StatusCode == 403)
{
content = String.Format("The url {0} returned access denied (403).", callback);
request.Message = content;
logService.Warn(request);
}
else if ((int)response.StatusCode == 404)
{
content = String.Format("The url {0} returned page not found (404).", callback);
request.Message = content;
logService.Warn(request);
}
else if ((int)response.StatusCode == 405)
{
content = String.Format("The url {0} returned 405 error. Please ensure the url is configured to accept http POST requests", callback);
request.Message = content;
logService.Warn(request);
}
else if ((int)response.StatusCode == 500)
{
content = String.Format("The url {0} returned a server error (500).", callback);
request.Message = content;
logService.Warn(request);
}
else
{
exceptionHandler.HandleError(ex);
content = String.Format("The url {0} returned an error: {1}", callback, ex.Message);
request.Message = content;
logService.Error(request);
}
}
else
{
exceptionHandler.HandleError(ex);
content = String.Format("The url {0} returned an error: {1}", callback, ex.Message);
request.Message = content;
logService.Error(request);
}
}
return content;
}
The problem is that no matter what, I always get a server error reported to me (through an e-mail reporting handler, but that is another story. I have the exception caught, and I am not re-throwing it, and yet I still get an error report.
Exception:
System.Net.WebException : Unable to connect to the remote server
Inner Exception Message:
System.Net.Sockets.SocketException : A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond [redacted]
The stack trace points to this line as the culprit in my PostHelper
using (Stream writeStream = request.GetRequestStream())
at System.Net.HttpWebRequest.GetRequestStream(TransportContext& context) at System.Net.HttpWebRequest.GetRequestStream()
Решение
You are getting a socket error. This error is happening before HTTP traffic is sent (hence, no status codes).
This block is going to get executed (hence your error email notification):
exceptionHandler.HandleError(ex);
content = String.Format("The url {0} returned an error: {1}", callback, ex.Message);
request.Message = content;
logService.Error(request);