异常处理的正确方式WebClient.DownloadString [英] Exception handling the right way for WebClient.DownloadString

查看:392
本文介绍了异常处理的正确方式WebClient.DownloadString的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道什么异常,我应该在使用保护自己反对 WebClient.DownloadString

下面是如何我目前正在使用它,但我敢肯定,你们可以提出更好更强大的异常处理。

例如,把我的头顶部:

  • 在没有互联网连接。
  • 服务器返回404。
  • 服务器超时。

什么是preferred的方式来处理这些案件,并抛出异常的用户界面?

 公开的IEnumerable<游戏> FindUpcomingGamesByPlatform(字符串平台)
{
    字符串的HTML;
    使用(Web客户端的客户端=新的Web客户端())
    {
        尝试
        {
            HTML = client.DownloadString(GetPlatformUrl(平台));
        }
        赶上(WebException E)
        {
            //我怎么抓住这个从UI显示在消息框中的错误?
            扔ê;
        }
    }

    串relevantHtml =&其中; TR>中+ GetHtmlFromThisYear(HTML);
    字符串[]分隔=新的String [] {< TR>中};
    字符串[] individualGamesHtml = relevantHtml.Split(分隔符,StringSplitOptions.None);

    返回ParseGames(individualGamesHtml);
}
 

解决方案

如果你发现 WebException ,它应处理大多数情况下。 Web客户端的HttpWebRequest 抛出一个 WebException 所有HTTP协议错误(4XX和5XX),也可用于网络级别的错误(断线,主机不可达,等等)


  

我如何抓住这从UI显示错误消息框?

我不知道我理解你的问题......你就不能表现出异常消息?

 的MessageBox.show(e.Message);
 

不要捕捉异常的 FindUpcomingGamesByPlatform ,让它泡了调用方法,抓住它那里,显示消息...

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

解决方案

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

这篇关于异常处理的正确方式WebClient.DownloadString的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆