Catch 500 internal server error with System.WebClient
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 I开发者_运维知识库IS. 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
}
}
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.
精彩评论