簡體   English   中英

如何捕獲“遠程服務器返回錯誤:(403)禁止。”的異常。

[英]how to catch the exception for “The remote server returned an error: (403) Forbidden.”

我收到“遠程服務器返回錯誤:(403)禁止。” 錯誤並想捕獲此異常。 我猜想HttpException塊應該捕獲它,如下所示,但事實並非如此。

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

我不想使用通用異常塊來捕獲此錯誤。 還有什么其他例外情況可以解決?

請參閱隨附的異常快照屏幕快照。

在此處輸入圖片說明

看起來異常被包裝在另一個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.
}

看一下堆棧跟蹤,而不用抓住它。 如果代碼不允許您不捕獲它,則將其打印到標准錯誤流中。 這將允許您查看異常類型並相應地進行try塊。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM