【发布时间】:2023-03-28 00:10:01
【问题描述】:
我有以下功能将通过代理为我获取某个网站的 html 源代码,它工作正常,除非服务器返回 503(服务器不可用)或任何其他异常,它永远不会进入 catch 语句。
在 catch 语句中,函数应该递归调用自身,最多 4 次,如果请求在 4 次尝试后仍然失败,则返回 null。
private static string GetPageHTML(string link,bool useprx)
{
int tryCount = 0;
WebClient client = new WebClient() { Proxy = new WebProxy(ProxyManager.GetProxy()) { Credentials = new NetworkCredential("xx", "xx") } };
try
{
return client.DownloadString(link);
}
catch (WebException ex)
{
var statuscode = ((HttpWebResponse)ex.Response).StatusCode;
{
if (tryCount == 3)
{
return null;
}
switch (statuscode)
{
case (HttpStatusCode.Forbidden):
tryCount++;
System.Threading.Thread.Sleep(5000);
return GetPageHTML(link, useprx);
case (HttpStatusCode.NotFound):
return null;
case (HttpStatusCode.GatewayTimeout):
tryCount++;
System.Threading.Thread.Sleep(5000);
return GetPageHTML(link, useprx);
case (HttpStatusCode.ServiceUnavailable) :
tryCount++;
System.Threading.Thread.Sleep(5000);
return GetPageHTML(link, useprx);
default: return null;
}
}
}
}
那么为什么它从不进入 catch 语句?
【问题讨论】:
-
让线程休眠 5 秒是浪费线程。如果你想等待,设置一个计时器或其他东西。
-
另外,您的
tryCount是本地人。当您递归调用该方法时,它会获得一个不同的本地。如果您的递归方法调用失败,它将再次调用自己,并使用一个新的本地。我想您会发现观察 tryCount 值为 3 应该是困难的。您可能想要重构并将计数作为参数传递,以便您可以跟踪它,或者最好重构潜在的进一步排除故障代码,以便您可以隔离它并在该故障点之外跟踪它。 -
@AnthonyPegram 没错,这也需要修复
标签: c# httpwebrequest try-catch system.net.webexception