我想知道在使用WebClient.DownloadString
时我应该保护自己的例外情况。
以下是我目前正在使用它的方式,但我相信你们可以建议更好的更强大的异常处理。
例如,脱离我的头顶:
处理这些情况并将异常抛出到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);
}
答案 0 :(得分:15)
如果你抓住WebException
,它应该处理大多数情况。 WebClient
和HttpWebRequest
为所有HTTP协议错误(4xx和5xx)抛出WebException
,并且还针对网络级错误(断开连接,主机无法访问等)抛出MessageBox.Show(e.Message);
如何从UI中捕获此内容以在消息框中显示错误?
我不确定我理解你的问题......难道你不能只显示异常消息吗?
FindUpcomingGamesByPlatform
不要在{{1}}中捕获异常,让它冒泡到调用方法,抓住它并显示消息......
答案 1 :(得分:5)
我使用此代码:
这里我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"));
}
回调
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
}
感谢。
答案 2 :(得分:1)
根据the MSDN documentation,唯一的非程序员例外是WebException
,如果出现以下情况可以引发:
组合BaseAddress和地址形成的URI无效。
-OR -
下载资源时出错。
答案 3 :(得分:0)
我通常这样处理,以打印远程服务器返回的任何异常消息。考虑到允许用户看到该值。
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);
}