WebClient.DownloadString 异常处理的正确方法
我想知道在使用 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);
}
I was wondering what exceptions I should protect myself against when using WebClient.DownloadString
.
Here's how I'm currently using it, but I'm sure you guys can suggest better more robust exception handling.
For example, off the top of my head:
- No internet connection.
- Server returned a 404.
- Server timed out.
What is the preferred way to handle these cases and throw the exception to the 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);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您捕获
WebException
,它应该可以处理大多数情况。WebClient
和HttpWebRequest
对于所有 HTTP 协议错误(4xx 和 5xx)以及网络级别错误(断开连接、主机无法访问)抛出WebException
, ETC)我不确定我是否理解你的问题...你不能只显示异常消息吗?
不要在
FindUpcomingGamesByPlatform
中捕获异常,让它冒泡到调用方法,在那里捕获它并显示消息...If you catch
WebException
, it should handle most cases.WebClient
andHttpWebRequest
throw aWebException
for all HTTP protocol errors (4xx and 5xx), and also for network level errors (disconnection, host not reachable, etc)I'm not sure I understand your question... Can't you just show the exception message?
Don't catch the exception in
FindUpcomingGamesByPlatform
, let it bubble up to the calling method, catch it there and show the message...我通常这样处理它以打印远程服务器返回的任何异常消息。鉴于允许用户看到该值。
I usually handle it like this to print any exception message the remote server is returning. Given that the users are allowed to see that value.
我使用以下代码:
这里我
init
加载事件中的网络客户端回调
谢谢。
I use this code:
Here I
init
the webclient whithin the loaded eventThe callback
Thanks.
根据 MSDN 文档,唯一的非程序员例外是
WebException
,如果出现以下情况,可能会引发该异常:According to the MSDN documentation, the only non-programmer exception is
WebException
, which can be raised if: