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

发布于 2024-11-07 08:03:45 字数 928 浏览 0 评论 0原文

我想知道在使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

℡Ms空城旧梦 2024-11-14 08:03:45

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


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

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

MessageBox.Show(e.Message);

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

If you catch WebException, it should handle most cases. WebClient and HttpWebRequest throw a WebException for all HTTP protocol errors (4xx and 5xx), and also for network level errors (disconnection, host not reachable, etc)


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

I'm not sure I understand your question... Can't you just show the exception message?

MessageBox.Show(e.Message);

Don't catch the exception in FindUpcomingGamesByPlatform, let it bubble up to the calling method, catch it there and show the message...

叹倦 2024-11-14 08:03:45

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

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);
}

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.

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);
}
∞梦里开花 2024-11-14 08:03:45

我使用以下代码:

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

    private void LayoutRoot_Loaded(对象发送者, RoutedEventArgs e)
    {
      // 从网络异步下载
      var client = new WebClient();
      client.DownloadStringCompleted += client_DownloadStringCompleted;
      client.DownloadStringAsync(new Uri("http://whateveraurisingis.com"));
    }
    
  2. 回调

    void client_DownloadStringCompleted(对象发送者,Dow​​nloadStringCompletedEventArgs e)
    {
      #region 处理下载错误
      字符串下载=空;
      尝试
      {
        下载 = e.Result;
      }
    catch(异常前)
      {
        MessageBox.Show(AppMessages.CONNECTION_ERROR_TEXT, AppMessages.CONNECTION_ERROR, MessageBoxButton.OK);
      }
    
      // 检查下载是否成功
      if(下载==空)
      {
        返回;
      }
      #endregion
    
      // 在我的示例中,我解析了上面下载的 xml 文档      
      // 解析下载的 xml 文档
      var dataDoc = XDocument.Load(new StringReader(下载));
    
      //...你的代码
    }
    

谢谢。

I use this code:

  1. Here I init the webclient whithin the loaded event

    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. The callback

    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
    }
    

Thanks.

拔了角的鹿 2024-11-14 08:03:45

根据 MSDN 文档,唯一的非程序员例外是 WebException,如果出现以下情况,可能会引发该异常:

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

-或-

下载资源时发生错误。

According to the MSDN documentation, the only non-programmer exception is WebException, which can be raised if:

The URI formed by combining BaseAddress and address is invalid.

-or-

An error occurred while downloading the resource.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文