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

Onl*_*ere 15 .net c# webclient

我想知道在使用时我应该保护自己的例外情况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);           
}
Run Code Online (Sandbox Code Playgroud)

Tho*_*que 15

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


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

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

MessageBox.Show(e.Message);
Run Code Online (Sandbox Code Playgroud)

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


Ogg*_*las 9

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

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);
}
Run Code Online (Sandbox Code Playgroud)


小智 5

我用这个代码:

  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"));
    }
    
    Run Code Online (Sandbox Code Playgroud)
  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
    }
    
    Run Code Online (Sandbox Code Playgroud)

谢谢.