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.
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).
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.
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.
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 } }
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