Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何捕获“的异常”;远程服务器返回错误:(403)禁止。”;_C# - Fatal编程技术网

C# 如何捕获“的异常”;远程服务器返回错误:(403)禁止。”;

C# 如何捕获“的异常”;远程服务器返回错误:(403)禁止。”;,c#,C#,我收到“远程服务器返回错误:(403)禁止。”错误,希望捕获此异常。我想HttpException块应该如下图所示捕获它,但它不是 catch (HttpException wex) { if (wex.GetHttpCode().ToString() == "403") //do stuff } 我不想使用泛型异常块来捕捉这个。还有什么例外可以抓住这个 请参阅附加的异常快照屏幕截图 在没有捕捉到堆栈跟踪的情况下查看堆栈跟踪。如果代码不允

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

catch (HttpException wex)
       {
       if (wex.GetHttpCode().ToString() == "403")
       //do stuff
       }
我不想使用泛型异常块来捕捉这个。还有什么例外可以抓住这个

请参阅附加的异常快照屏幕截图


在没有捕捉到堆栈跟踪的情况下查看堆栈跟踪。如果代码不允许您不捕获它,请将其打印到标准错误流。这将允许您查看异常类型,并相应地执行
try
块。

看起来异常被包装在另一个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);
}
static T GetNestedException(Exception ex),其中T:Exception
{
如果(ex==null){returnnull;}
var-tEx=ex as T;
如果(tEx!=null){return tEx;}
返回GetNestedException(例如InnerException);
}
然后,可以使用此捕捉块:

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.
}
catch(异常示例)
{
var wex=GetNestedException(ex);
//如果没有嵌套的WebException,请重新引发该异常。
如果(wex==null){throw;}
//获取响应对象。
var response=wex.response作为HttpWebResponse;
//如果不是HTTP响应或不是错误403,请重新抛出。
if(response==null | | response.StatusCode!=HttpStatusCode.Forbidden){
投掷;
}
//错误是403。请在此处处理。
}

它的可能副本确实应该捕获异常(如果抛出了
HttpException
,可能是
WebException
),但我不知道为什么在可以测试
wex.GetHttpCode()的情况下调用
.ToString()
)==403
。自行查找:中断调试器并查找异常的类型,或者使用临时的
捕获(异常异常)
控制台。WriteLine(exception.GetType().Name)
@cdhowie在这里给了您正确的答案,这是一个WebException。我也尝试过捕获这个块,但它也不起作用(System.Net.WebException-wex)