gpt4 book ai didi

c# - 异常处理 WebClient.DownloadString 的正确方法

转载 作者:可可西里 更新时间:2023-11-01 07:54:37 27 4
gpt4 key购买 nike

我想知道在使用 WebClient.DownloadString 时我应该保护自己免受哪些异常的影响。

这是我目前使用它的方式,但我相信你们可以建议更好、更健壮的异常处理。

例如,在我的脑海中:

  • 没有互联网连接。
  • 服务器返回 404。
  • 服务器超时。

处理这些情况并将异常抛出到 UI 的首选方法是什么?

public IEnumerable<Game> FindUpcomingGamesByPlatform(string platform)
{
string html;
using (WebClient client = new WebClient())
{
try
{
html = client.DownloadString(GetPlatformUrl(platform));
}
catch (WebException e)
{
//How do I capture this from the UI to show the error in a message box?
throw e;
}
}

string relevantHtml = "<tr>" + GetHtmlFromThisYear(html);
string[] separator = new string[] { "<tr>" };
string[] individualGamesHtml = relevantHtml.Split(separator, StringSplitOptions.None);

return ParseGames(individualGamesHtml);
}

最佳答案

如果您捕捉到 WebException,它应该可以处理大多数情况。 WebClientHttpWebRequest 为所有 HTTP 协议(protocol)错误(4xx 和 5xx)抛出一个 WebException,也为网络级错误(断开连接,主机不可达)等)


How do I capture this from the UI to show the error in a message box?

我不确定我是否理解您的问题...您不能只显示异常消息吗?

MessageBox.Show(e.Message);

不要在 FindUpcomingGamesByPlatform 中捕获异常,让它冒泡到调用方法,在那里捕获它并显示消息...

关于c# - 异常处理 WebClient.DownloadString 的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5999215/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com