2011-05-14 4 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

편집을 참조하십시오. –

+0

updated my answer –

+0

감사합니다. Thomas, 예외 오류를 버블 링하는 방법을 묻는 것 같아요. :) –

1

the MSDN documentation에 따르면, 유일한 비 프로그래머는 예외입니다 WebException 다음 경우에 발생시킬 수 있습니다.

BaseAddress와 주소를 결합하여 형성된 URI가 유효하지 않습니다.

-or-

리소스를 다운로드하는 중 오류가 발생했습니다.

5

은이 코드를 사용 : 여기

  1. 내가로드 이벤트

    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. 콜백 이내에서 웹 클라이언트를 init

    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 
    } 
    
,

감사합니다.