Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exception handling the right way for WebClient.DownloadString

Tags:

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);            } 
like image 573
Only Bolivian Here Avatar asked May 14 '11 01:05

Only Bolivian Here


People also ask

What does WebClient Downloadstring do?

This method retrieves the specified resource. After it downloads the resource, the method uses the encoding specified in the Encoding property to convert the resource to a String. This method blocks while downloading the resource.

What are the four keywords for exception handling?

C# exception handling is built upon four keywords: try, catch, finally, and throw.

What is WebClient class in C#?

The WebClient class provides common methods for sending data to or receiving data from any local, intranet, or Internet resource identified by a URI. The WebClient class uses the WebRequest class to provide access to resources.


2 Answers

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

like image 185
Thomas Levesque Avatar answered Sep 20 '22 15:09

Thomas Levesque


I use this code:

  1. Here I init the webclient whithin the loaded event

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

    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 } 

Thanks.

like image 39
Avatar2012 Avatar answered Sep 17 '22 15:09

Avatar2012