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:
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); }
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.
C# exception handling is built upon four keywords: try, catch, finally, and throw.
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.
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...
I use this code:
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")); }
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With