【问题标题】:how to catch the exception for "The remote server returned an error: (403) Forbidden."如何捕获“远程服务器返回错误:(403)禁止”的异常。
【发布时间】:2013-09-06 15:54:14
【问题描述】:

我收到“远程服务器返回错误:(403) Forbidden。”错误并希望捕获此异常。我猜 HttpException 块应该如下所示捕获它,但它不是。

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

我不想使用通用异常块来捕获它。还有什么异常可以捕捉到这个?

请参阅附件中的异常快照截图。

【问题讨论】:

  • 确实它应该捕获异常(如果 HttpException 被抛出 - 也许它是 WebException 而不是),虽然我不知道你为什么在这里调用 .ToString()可以测试wex.GetHttpCode() == 403
  • 自己找出来:打破调试器并找出异常的类型,或者使用临时的catch (Exception exception)Console.WriteLine(exception.GetType().Name)
  • @cdhowie 在这里给了你正确的答案,这是一个 WebException。
  • 我也尝试过这个块,但它也不起作用(System.Net.WebException wex)

标签: c#


【解决方案1】:

看起来异常被包装在另一个 API 级异常对象中。您可以有条件地捕获您所追求的特定异常,否则重新抛出。使用这个助手:

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

然后你可以使用这个 catch 块:

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

【讨论】:

    【解决方案2】:

    看看堆栈跟踪,而不是你抓住它。如果代码不允许您不捕获它,并将其打印到标准错误流中。这将允许您查看异常类型并相应地执行 try 阻止。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-08-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-08
      相关资源
      最近更新 更多