2

I have some code that does DownloadStringAsync. with my brower i can get some information about the error since I turned on send error message to browser in IIS. I was wondering if it's possible to catch it in the code.

void Process( Job job )
{
   using( WebClient client = new WebClient() )
   {
        client.DownloadStringCompleted += (sender, args ) =>
            DownloadStringCompleted(job,args);

        try
        {
            client.DownloadStringAsync(new Uri(job.url), job);
        }
        catch (WebException e)
        {
            Console.WriteLine(e.Message);
        }
   }
}

void DownloadStringCompleted(Job job, DownloadStringCompletedEventArgs args)
{
   if( args.Error != null )
   {
       // How can i get the response ? Like 500 Internal Server Error
       // this_buggy_page.asp Line 100000
   }
}
Guillaume Massé
  • 8,004
  • 8
  • 44
  • 57

1 Answers1

4

If args.Error != null it will likely contain an instance of WebException; if this is the case, then you can cast it to WebException, then access its Response property, which you can cast to HttpWebResponse (for HTTP calls), and from there you can get the headers / body / etc.

Kirk Woll
  • 76,112
  • 22
  • 180
  • 195
carlosfigueira
  • 85,035
  • 14
  • 131
  • 171