3

Although I've almost done it, this code doesn't exactly work for what I want to do. Is there a way I can catch specifically error code 403 in this catch block?

catch (WebException e)
{
    if (e.Status == WebExceptionStatus.ProtocolError)
    {
        Logger.Error(e.ToString());
        Console.ReadKey(true);
        return;
    }

    throw;
}
carbin
  • 77
  • 7
  • Duplicate of https://stackoverflow.com/questions/7440922/get-error-number-in-webexception-error – Hitesh Kansagara Apr 24 '18 at 04:14
  • 3
    Possible duplicate of [Get Error number in WebException Error](https://stackoverflow.com/questions/7440922/get-error-number-in-webexception-error) – hungrykoala Apr 24 '18 at 04:16

1 Answers1

4

You can change your code to check the status like this:

catch (WebException e)
{
    if (e.Status == WebExceptionStatus.ProtocolError
          && (HttpWebResponse)e.Response).StatusCode == HttpStatusCode.Forbidden)
    {
        Logger.Error(e.ToString());
        Console.ReadKey(true);
        return;
    }

    throw;
}

But, since you're just rethrowing if it isn't Forbidden, and assuming you're using C# 6 or newer, you can make your catch conditional like so:

try
{
    // code
}
catch (WebException e) 
    when (e.Status == WebExceptionStatus.ProtocolError 
          && (HttpWebResponse)e.Response).StatusCode == HttpStatusCode.Forbidden)
{
    Logger.Error(e.ToString());
    Console.ReadKey(true);
    return;
}
ProgrammingLlama
  • 36,677
  • 7
  • 67
  • 86
  • The use of the exception filter should be preferred since it's less code. we've had it for 3 years and it's not avant garde anymore – Aluan Haddad Apr 24 '18 at 04:42
  • 1
    @Aluan True, but a few years ago I worked at a company whose flagship product was stuck on .NET Framework 2.0 due to third party components that were key to the system but no longer maintained, so it seemed wise to provide both options to OP since we don't know their situation. – ProgrammingLlama Apr 24 '18 at 06:07