how to catch the exception for “The remote server

2020-04-19 06:11发布

I m getting "The remote server returned an error: (403) Forbidden." error and want to catch this exception. I guess HttpException block should trap it as shown below but its not.

catch (HttpException wex)
       {
       if (wex.GetHttpCode().ToString() == "403")
       //do stuff
       }

I don't want to use generic exception block to catch this. What other exception could catch this?

See the attached the exception snapshotscreenshot.

enter image description here

标签: c#
2条回答
家丑人穷心不美
2楼-- · 2020-04-19 06:16

It looks like the exception is being wrapped inside of another API-level exception object. You can conditionally catch the specific exception you are after and re-throw otherwise. Using this helper:

static T GetNestedException<T>(Exception ex) where T : Exception
{
    if (ex == null) { return null; }

    var tEx = ex as T;
    if (tEx != null) { return tEx; }

    return GetNestedException<T>(ex.InnerException);
}

You can then use this catch block:

catch (Exception ex)
{
    var wex = GetNestedException<WebException>(ex);

    // If there is no nested WebException, re-throw the exception.
    if (wex == null) { throw; }

    // Get the response object.
    var response = wex.Response as HttpWebResponse;

    // If it's not an HTTP response or is not error 403, re-throw.
    if (response == null || response.StatusCode != HttpStatusCode.Forbidden) {
        throw;
    }

    // The error is 403.  Handle it here.
}
查看更多
够拽才男人
3楼-- · 2020-04-19 06:25

Take a look at the stacktrace without you catching it. If the code doesn't allow you to not catch it, and print it out to standard error stream. This will allow you to see the exception type and do your try block accordingly.

查看更多
登录 后发表回答