处理WebClient.DownloadString的正确方法的exception

我想知道在使用WebClient.DownloadString时我应该保护自己的exception。

这是我目前正在使用它的方式,但我相信你们可以建议更好的更强大的exception处理。

例如,我的头顶:

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

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

 public IEnumerable 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 = "" + GetHtmlFromThisYear(html); string[] separator = new string[] { "" }; string[] individualGamesHtml = relevantHtml.Split(separator, StringSplitOptions.None); return ParseGames(individualGamesHtml); } 

如果你捕获WebException ,它应该处理大多数情况。 WebClientHttpWebRequest为所有HTTP协议错误(4xx和5xx)抛出WebException ,也为网络级错误(断开连接,主机无法访问等)抛出WebException


如何从UI捕获此信息以在消息框中显示错误?

我不确定我理解你的问题……难道你不能只显示exception消息吗?

 MessageBox.Show(e.Message); 

不要在FindUpcomingGamesByPlatform捕获exception,让它冒泡到调用方法,在那里捕获它并显示消息……

我用这个代码:

  1. 在这里,我在加载的事件中init webclient

     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")); } 
  2. 回调

     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 } 

谢谢。

根据MSDN文档 ,唯一的非程序员exception是WebException ,可以在以下情况下引发:

通过组合BaseAddress和地址形成的URI无效。

-要么-

下载资源时发生错误。