Properly handling HttpClient exceptions within async / await

Nils Holtar picture Nils Holtar · Sep 26, 2013 · Viewed 61.6k times · Source

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.

Answer

mirushaki picture mirushaki · Sep 2, 2014

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