Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I catch a 404?

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.

like image 676
JL. Avatar asked Dec 22 '09 22:12

JL.


People also ask

How do I find a 404 page?

The easy way is to use Google search console to find all 404 pages and fix them. To find the list of all 404 pages, you can log in to the Google search console account. Go to your Website dashboard under Google search console. Under error you would see “Submitted URL not found (404).

What happens when you call 404?

404 is a status code that tells a web user that a requested page is not available. 404 and other response status codes are part of the web's Hypertext Transfer Protocol response codes. The 404 code means that a server could not find a client-requested webpage.

How does fetch handle 404?

The Promise returned from fetch() won't reject on HTTP error status even if the response is an HTTP 404 or 500. Instead, it will resolve normally (with ok status set to false), and it will only reject on network failure or if anything prevented the request from completing.


1 Answers

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     } } 
like image 167
John Saunders Avatar answered Sep 20 '22 21:09

John Saunders