How can I catch a 404?

C#.NetException HandlingError HandlingHttp Status-Code-404

C# Problem Overview


I have the following code:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "HEAD";
request.Credentials = MyCredentialCache;

try
{
    request.GetResponse();
}
catch
{
}

How can I catch a specific 404 error? The WebExceptionStatus.ProtocolError can only detect that an error occurred, but not give the exact code of the error.

For example:

catch (WebException ex)
{
    if (ex.Status != WebExceptionStatus.ProtocolError)
    {
        throw ex;
    }
}

Is just not useful enough... the protocol exception could be 401, 503, 403, anything really.

C# Solutions


Solution 1 - C#

try
{
    var request = WebRequest.Create(uri);
    using (var response = request.GetResponse())
    {
        using (var responseStream = response.GetResponseStream())
        {
            // Process the stream
        }
    }
}
catch (WebException ex)
{
    if (ex.Status == WebExceptionStatus.ProtocolError &&
        ex.Response != null)
    {
        var resp = (HttpWebResponse) ex.Response;
        if (resp.StatusCode == HttpStatusCode.NotFound)
        {
            // Do something
        }
        else
        {
            // Do something else
        }
    }
    else
    {
        // Do something else
    }
}

Solution 2 - C#

Use the HttpStatusCode Enumeration, specifically HttpStatusCode.NotFound

Something like:

HttpWebResponse errorResponse = we.Response as HttpWebResponse;
if (errorResponse.StatusCode == HttpStatusCode.NotFound) {
  //
}

Where
we is a WebException.

Solution 3 - C#

In C# 6 you can use exception filters.

try
{
    var request = WebRequest.Create(uri);
    using (var response = request.GetResponse())
    using (var responseStream = response.GetResponseStream())
    {
        // Process the stream
    }
}
catch(WebException ex) when ((ex.Response as HttpWebResponse)?.StatusCode == HttpStatusCode.NotFound)
{
    // handle 404 exceptions
}
catch (WebException ex)
{
    // handle other web exceptions
}

Solution 4 - C#

I haven't tested this, but it should work

try
{
    // TODO: Make request.
}
catch (WebException ex)
{
    if (ex.Status == WebExceptionStatus.ProtocolError) {
        HttpWebResponse resp = ex.Response as HttpWebResponse;
        if (resp != null && resp.StatusCode == HttpStatusCode.NotFound)
        {
            // TODO: Handle 404 error.
        }
        else
            throw;
    }
    else
        throw;
}

Solution 5 - C#

I think if you catch a WebException there is some information in there that you can use to determine if it was a 404. That's the only way I know of at the moment...I'd be interested in knowing any others...

catch(WebException e) {
    if(e.Status == WebExceptionStatus.ProtocolError) {
        var statusCode = (HttpWebResponse)e.Response).StatusCode);
        var description = (HttpWebResponse)e.Response).StatusDescription);
    }
}

Solution 6 - C#

Check out this snipit. The GetResponse will throw a WebRequestException. Catch that and you can get the status code from the response.

try {
   // Create a web request for an invalid site. Substitute the "invalid site" strong in the Create call with a invalid name.
     HttpWebRequest myHttpWebRequest = (HttpWebRequest) WebRequest.Create("invalid site");

    // Get the associated response for the above request.
     HttpWebResponse myHttpWebResponse = (HttpWebResponse) myHttpWebRequest.GetResponse();
    myHttpWebResponse.Close();
}
catch(WebException e) {
    Console.WriteLine("This program is expected to throw WebException on successful run."+
                        "\n\nException Message :" + e.Message);
    if(e.Status == WebExceptionStatus.ProtocolError) {
        Console.WriteLine("Status Code : {0}", ((HttpWebResponse)e.Response).StatusCode);
        Console.WriteLine("Status Description : {0}", ((HttpWebResponse)e.Response).StatusDescription);
    }
}
catch(Exception e) {
    Console.WriteLine(e.Message);
}

this came from http://msdn.microsoft.com/en-us/library/system.net.webexception.status.aspx

Solution 7 - C#

See at MSDN about status of the response:

...
catch(WebException e) {
  Console.WriteLine("The following error occured : {0}",e.Status);  
}
...

       

Solution 8 - C#

Catch the proper exception type WebException:

try
{
    var request = (HttpWebRequest) WebRequest.Create(String.Format("http://www.gravatar.com/avatar/{0}?d=404", hashe));

    using(var response = (HttpWebResponse)request.GetResponse())
        Response.Write("has avatar");
}
catch(WebException e) 
{
  if(e.Response.StatusCode == 404) 
    Response.Write("No avatar");
}

Solution 9 - C#

For VB.NET folks browsing this, I believe we can catch the exception only if it truly is a 404. Something like:

Try
    httpWebrequest.GetResponse()
Catch we As WebException When we.Response IsNot Nothing _
                              AndAlso TypeOf we.Response Is HttpWebResponse _
                              AndAlso (DirectCast(we.Response, HttpWebResponse).StatusCode = HttpStatusCode.NotFound)
    
    ' ...

End Try

Solution 10 - C#

when POST or GET data to the server using WebRequest class then the type of exception would be WebException.Below is the code for file not found exception

//Create a web request with the specified URL
string path = @"http://localhost/test.xml1";
WebRequest myWebRequest = WebRequest.Create(path);

//Senda a web request and wait for response.
try
{
  WebResponse objwebResponse = myWebRequest.GetResponse();
  Stream stream= objwebResponse.GetResponseStream();
}
catch (WebException ex) {
  if (((HttpWebResponse)(ex.Response)).StatusCode == HttpStatusCode.NotFound) {
    throw new FileNotFoundException(ex.Message);
  }
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJL.View Question on Stackoverflow
Solution 1 - C#John SaundersView Answer on Stackoverflow
Solution 2 - C#Jay RiggsView Answer on Stackoverflow
Solution 3 - C#craftworkgamesView Answer on Stackoverflow
Solution 4 - C#MiffTheFoxView Answer on Stackoverflow
Solution 5 - C#mezoidView Answer on Stackoverflow
Solution 6 - C#Jonathan S.View Answer on Stackoverflow
Solution 7 - C#DrorView Answer on Stackoverflow
Solution 8 - C#Nick CraverView Answer on Stackoverflow
Solution 9 - C#unnknownView Answer on Stackoverflow
Solution 10 - C#Sheo Dayal SinghView Answer on Stackoverflow