Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catch 403 WebException in trycatch blocks?

Tags:

c#

.net

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;
}

1 Answers

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;
}
like image 160
DiplomacyNotWar Avatar answered Jun 23 '26 07:06

DiplomacyNotWar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!