【问题标题】:Exception handling the right way for WebClient.DownloadStringWebClient.DownloadString 的异常处理正确方法
【发布时间】:2011-08-25 08:20:04
【问题描述】:

我想知道在使用 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);           
}

【问题讨论】:

    标签: c# .net webclient


    【解决方案1】:

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


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

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

    MessageBox.Show(e.Message);
    

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

    【讨论】:

    • 谢谢托马斯,我想我在问如何冒泡异常错误。 :)
    【解决方案2】:

    根据the MSDN documentation,唯一的非程序员异常是WebException,可以在以下情况下引发:

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

    -或-

    下载资源时出错。

    【讨论】:

      【解决方案3】:

      我使用这个代码:

      1. 我在这里init 加载事件中的网络客户端

        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
        }
        

      谢谢。

      【讨论】:

        【解决方案4】:

        我通常这样处理它以打印远程服务器返回的任何异常消息。鉴于允许用户查看该值。

        try
        {
            getResult = client.DownloadString(address);
        }
        catch (WebException ex)
        {
            String responseFromServer = ex.Message.ToString() + " ";
            if (ex.Response != null)
            {
                using (WebResponse response = ex.Response)
                {
                    Stream dataRs = response.GetResponseStream();
                    using (StreamReader reader = new StreamReader(dataRs))
                    {
                        responseFromServer += reader.ReadToEnd();
                    }
                }
            }
            _log.Error("Server Response: " + responseFromServer);
            MessageBox.Show(responseFromServer);
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-11-07
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多