25

I was hoping somebody could enlighten me a little bit on an issue I am facing in regards to async/await exception handling with HttpClient. I have written some code to illustrate, and it is being excecuted on both a Windows Phone 8 device and the emulator:

    private async void SearchButton_Click(object sender, EventArgs e)
    {
        try
        {
            HttpClient client = new HttpClient();
            System.Diagnostics.Debug.WriteLine("BEGIN FAULTY REQUEST:");
            string response = await client.GetStringAsync("http://www.ajshdgasjhdgajdhgasjhdgasjdhgasjdhgas.tk/");
            System.Diagnostics.Debug.WriteLine("SUCCESS:");
            System.Diagnostics.Debug.WriteLine(response);
        }
        catch (Exception exception)
        {
            System.Diagnostics.Debug.WriteLine("CAUGHT EXCEPTION:");
            System.Diagnostics.Debug.WriteLine(exception);
        }
    }

Tapping the button that invokes this function, produces the following output in the debugger console, the most interesting being the ones in bold:

BEGIN FAULTY REQUEST:

An exception of type 'System.Net.WebException' occurred in System.Windows.ni.dll and wasn't handled before a managed/native boundary

An exception of type 'System.Net.WebException' occurred in System.Windows.ni.dll and wasn't handled before a managed/native boundary

A first chance exception of type 'System.Net.Http.HttpRequestException' occurred in mscorlib.ni.dll

An exception of type 'System.Net.Http.HttpRequestException' occurred in mscorlib.ni.dll and wasn't handled before a managed/native boundary

CAUGHT EXCEPTION:

(and here it prints out the HttpRequestException)

Of course I am expecting an error in this case since the URL I am calling is nonsense. What I am not understanding here, is why the debugger reports that the exceptions are not handled, when the output simultaneously reports that the exception is caught. Also, the UI side of the app becomes much less responsive while the output is being printed, indicating that something is probably amiss.

Is this not the way to handle exceptions when working with async and await? I appreciate any input! Thanks.

Community
  • 1
  • 1
Nils Holtar
  • 253
  • 1
  • 3
  • 4
  • 2
    As far as the responsiveness you shouldn't run long processes in a UI event. These should be quick and long running processes should be completed in another thread. Try the `BackgroundWorker` http://msdn.microsoft.com/en-us/library/System.ComponentModel.BackgroundWorker.aspx – Harrison Sep 26 '13 at 17:13

3 Answers3

44

As you are using HttpClient, try to use response.EnsureSuccessStatusCode();

Now HttpClient will throw exception when response status is not a success code.

try
{
    HttpResponseMessage response = await client.GetAsync("http://www.ajshdgasjhdgajdhgasjhdgasjdhgasjdhgas.tk/");
    response.EnsureSuccessStatusCode();    // Throw if not a success code.

    // ...
}
catch (HttpRequestException e)
{
    // Handle exception.
}

ORIGINAL SOURCE OF THE CODE: http://www.asp.net/web-api/overview/advanced/calling-a-web-api-from-a-net-client

Matt
  • 3,588
  • 2
  • 24
  • 38
mirushaki
  • 597
  • 1
  • 6
  • 11
  • 3
    If you want `response`to be of type `HttpResponseMessage` you must use `client.GetAsync`instead of `client.GetStringAsync`. – kaolick Oct 17 '14 at 15:10
  • I have been trying to catch Bad Requests (400) as exceptions. In my case, my app not hitting a valid endpoint for the webserver (maybe because the server hasn't changed it). I've been scratching my head for a half hour, Googling why this doesn't catch as an exception. Your answer really helped. Is this the proper way to be dealing with this sort of thing? Catching a Bad Request as an exception? Thank you. – Chucky Nov 09 '18 at 12:06
11

This is an artifact of the debugger. It's determining that an exception is "uncaught" because it's not caught yet. In this case this is expected behavior.

You are handling the exceptions correctly.

Stephen Cleary
  • 376,315
  • 69
  • 600
  • 728
  • 2
    I'd say it is marked "uncaught" because it was not caught by user code, but by the TPL. – usr Sep 26 '13 at 20:15
  • The exception is not handled. it is hidden (even though it is logged to Debug.WriteLine which will not appear in Release mode). When built in release, if the http call fails, you will not know why (or even that it failed). – Stuart Jan 20 '17 at 16:00
  • @Stuart: For the code posted in the question, the exception will be caught. – Stephen Cleary Jan 20 '17 at 18:26
0

The debugger is telling you that this exception is first chance. When a debugger is attached to your process it gets notified for every exception that is thrown and then based on how the debugger has been configured it will decide what to do with it. You can go through What is first chance exception? for more details.

On a side note, catch specific exceptions only so that you understand which exceptions you are expecting and why.

Anupam
  • 840
  • 4
  • 9
  • 19
  • Thanks, I will have a read! And I agree on your side note, my actual scenario is different, I just wrote this to illustrate my problem. – Nils Holtar Sep 27 '13 at 09:43