Dr_Berry721
Dr_Berry721

Reputation: 69

Error Handling for WebRequest & Response

I am currently running a method that takes a string (a domain name) and checks to see if the site is available or not and passes the information into a Domain object I have created. Currently, I am running into an issue where one of the sites is down and is in turn crashing the application. Below is the method:

private Domain GetStatus(string x)
    {
        string status = "";

        WebRequest req = HttpWebRequest.Create("http://www." + x);
        WebResponse res = req.GetResponse();
        HttpWebResponse response = (HttpWebResponse)res;
        if ((int)response.StatusCode > 226 || response.StatusCode == HttpStatusCode.NotFound)
        {
            status = "ERROR: " + response.StatusCode.ToString();
        }
        else
        {
            status = "LIVE";
        }

        Domain temp = new Domain(x, status);
        return temp;
    }

Initial thoughts were that the response.StatusCode == HttpStatusCode.NotFound would handle such an error but it is currently crashing on the line WebResponse res = req.GetResponse(); with the following response:

System.Net.WebException: 'The remote name could not be resolved: 'www.DOMAIN.com''

Upvotes: 2

Views: 6353

Answers (3)

Mikhail Ionkin
Mikhail Ionkin

Reputation: 617

To handle HTTP error you can intercept WebException and then use Response field

https://learn.microsoft.com/en-us/dotnet/api/system.net.webexception.response?view=net-7.0

catch (WebException ex)
{ 
   try { 
       string responseBody;
       using (StreamReader strr = new StreamReader(ex.Response.GetResponseStream()))
           responseBody = strr.ReadToEnd();
       logger.Warn("response body: " + responseBody);
   } catch (Exception ...) {  ... }
} 

Upvotes: 0

Orel Eraki
Orel Eraki

Reputation: 12196

HttpWebRequest is all about HTTP protocol, which is kind of a agreed upon language.

But if the person on the other end doesn't exists, so how should you expect him to return you an "Hello" for example ?

So StatusCode is really just about if the actual remote site did response, what did the response state was according to the request resource, is it Successful(200) ? Not Found(404) ? Unauthorized(401) and so on.

Exception means, i couldn't reach the site because of many reasons. StatusCode means the resource you requested has return this response type.

But a more actual check if the site is alive or not, is querying a static page and not getting exception, a more healthy check, will querying a static page, you will always count as being Healthy; meaning will return a 200 OK response.

So it all depends on what LIVE means for you (or the client using it).

Is it the remote host is actually receiving requests, meaning no Exceptions. Or it actually means, he's able to get requests and returning me a valid StatusCode response that i expect him to return (Healthy).

Upvotes: 1

Stefan
Stefan

Reputation: 17648

The issue is due to the fact that your own code is raising an exception.

This can be due to the lack of an internet connection, or a dns resolve issue (which could be caused by the remote party).

So, if the remote server throws an error, you'll get HTTP 500 Internal Server Error, if you can't reach it; your code throws an exception and you'll need to handle that.

To fix this, you can use a try/catch block, something like this:

private Domain GetStatus(string x)
{
    string status = "";

    try
    {    
         WebRequest req = HttpWebRequest.Create("http://www." + x);
         WebResponse res = req.GetResponse();
         HttpWebResponse response = (HttpWebResponse)res;
         if ((int)response.StatusCode > 226 || 
             response.StatusCode ==  HttpStatusCode.NotFound)
         {
             status = "ERROR: " + response.StatusCode.ToString();
         }
         else
         {
             status = "LIVE";
         }
     }
     catch (Exception e)
     {
          status = "ERROR: Something bad happend: " + e.ToString();
     }

     Domain temp = new Domain(x, status);
     return temp;
}


By the way, the message,

The remote name could not be resolved

indicates that the host cannot be resolved.

Most likely cause is that your internet is down or, the domain is misspelled or the route to the domain is faulty (e.g. on intranet environments).

Upvotes: 1

Related Questions