2011-05-14 323 views
13

我想知道什麼例外,我應該保護自己以防止使用WebClient.DownloadString異常處理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);   
} 

回答

13

如果你趕上WebException,它應該處理大多數情況。 WebClientHttpWebRequest拋出所有的HTTP協議錯誤(4XX和5XX)一WebException,也爲網絡級別的錯誤(斷線,主機不可達等)


如何從UI捕捉這在消息框中顯示錯誤?

我不知道我理解你的問題......你不能只顯示異常消息嗎?

MessageBox.Show(e.Message); 

不要捕獲異常的FindUpcomingGamesByPlatform,讓它泡了調用方法,抓住它存在並顯示消息...

+0

請參閱編輯。 – 2011-05-14 01:22:41

+0

更新了我的回答 – 2011-05-14 01:26:47

+0

謝謝托馬斯,我想我是問如何冒泡異常錯誤。 :) – 2011-05-14 01:33:14

1

the MSDN documentation,唯一的非程序員的例外是WebException,如果其可以被升高:

的URI通過組合BaseAddress和地址形成是無效的。

- 或 -

下載資源時發生錯誤。

5

我用這個代碼:

  1. 這裏我init WebClient的whithin Loaded事件

    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 
    } 
    

謝謝。