1

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?

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Jared Price
  • 5,217
  • 7
  • 44
  • 74
  • Does this help? http://stackoverflow.com/questions/692342/net-httpwebrequest-getresponse-raises-exception-when-http-status-code-400-ba –  Oct 06 '14 at 19:12
  • 1
    Probably because of this asynchronous thing where different things happen on different threads? – Uwe Keim Oct 06 '14 at 19:16

1 Answers1

0

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);
}
});
Community
  • 1
  • 1
aleha_84
  • 8,309
  • 2
  • 38
  • 46