我收到“远程服务器返回错误:(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.
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)