简体   繁体   中英

C# Unhandled Exception using try catch block

I'm getting a System.Net.WebException saying:

The remote server returned an error: (403) Forbidden.

This is what I'm expecting since invalid headers are being passed in with the http request. However, my code does not seem to be catching the exception like I would expect.

Here is the code:

private void callback(IAsyncResult result)
{
    Debug.WriteLine("Callback");
    HttpWebResponse response = null;
    try
    {
        response = (result.AsyncState as HttpWebRequest).EndGetResponse(result) 
                       as HttpWebResponse;
    }
    catch (WebException e)
    {
        Debug.WriteLine("Exception: " + e);
    }
    catch (Exception e)
    {
        Debug.WriteLine("Unknown exception: " + e);
    }
}

Why is the exception not caught?

Take a look here .

Probably you should do something like this:

Task<WebResponse> task = Task.Factory.FromAsync(
    request.BeginGetResponse,
    asyncResult => { callback(asyncResult); },
    (object)null);

return task.ContinueWith(t =>
{
if (t.IsFaulted)
{
    //handle error
    Exception firstException = t.Exception.InnerExceptions.First();
}
else
{
    return FinishWebRequest(t.Result);
}
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM