异常处理WebClient.DownloadString的正确方式
问题描述:
我想知道什么例外,我应该保护自己以防止使用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);
}
答
如果你赶上WebException
,它应该处理大多数情况。 WebClient
和HttpWebRequest
抛出所有的HTTP协议错误(4XX和5XX)一WebException
,也为网络级别的错误(断线,主机不可达等)
如何从UI捕捉这在消息框中显示错误?
我不知道我理解你的问题......你不能只显示异常消息吗?
MessageBox.Show(e.Message);
不要捕获异常的FindUpcomingGamesByPlatform
,让它泡了调用方法,抓住它存在并显示消息...
答
据the MSDN documentation,唯一的非程序员的例外是WebException
,如果其可以被升高:
的URI通过组合BaseAddress和地址形成是无效的。
- 或 -
下载资源时发生错误。
答
我用这个代码:
-
这里我
init
WebClient的whithin Loaded事件private void LayoutRoot_Loaded(object sender, RoutedEventArgs e) { // download from web async var client = new WebClient(); client.DownloadStringCompleted += client_DownloadStringCompleted; client.DownloadStringAsync(new Uri("http://whateveraurisingis.com")); }
-
回调
void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) { #region handle download error string download = null; try { download = e.Result; } catch (Exception ex) { MessageBox.Show(AppMessages.CONNECTION_ERROR_TEXT, AppMessages.CONNECTION_ERROR, MessageBoxButton.OK); } // check if download was successful if (download == null) { return; } #endregion // in my example I parse a xml-documend downloaded above // parse downloaded xml-document var dataDoc = XDocument.Load(new StringReader(download)); //... your code }
谢谢。
请参阅编辑。 – 2011-05-14 01:22:41
更新了我的回答 – 2011-05-14 01:26:47
谢谢托马斯,我想我是问如何冒泡异常错误。 :) – 2011-05-14 01:33:14