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