Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpClient - dealing with aggregate exceptions

Hi i am using HttpClient similar to this:

public static Task<string> AsyncStringRequest(string url, string contentType)
{
    try
    {
        var client = new HttpClient();
        client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue(contentType));

        return client.GetStringAsync(url).ContinueWith(task => {
            return task.Result;
        });
    }
    catch (AggregateException ex)
    {
        throw ex;
    }
    catch (WebException ex)
    {
        throw ex;
    }       
    catch (Exception ex)
    {
        throw ex;
    }
}

But i am having difficulties dealing with exceptions. I have added the additional catch blocks just to try and step throw, but none of the break points are caught in any of the catch blocks. I realise using Task the exception could occur on a different thread than the caller so the exception is wrapped in a aggregate container, but i am not sure what the best way to deal with these exceptions is.

For example i make a request to a web service and specific an invalid parameter in the request, and an exception is thrown. I want to me able to catch the aggregate exceptions and look at the innerexceptions to work out why the request has failed and return a friendly message.

So my question is, what is the best way to catch these aggregate exceptions and deal with them?

like image 846
gdp Avatar asked Jun 28 '12 07:06

gdp


1 Answers

The exception is thrown by task.Result:

var client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(...);
return client.GetStringAsync(url).ContinueWith(task =>
{
    try
    {
        return task.Result;
    }
    catch (AggregateException ex)
    {
        throw ex;
    }
    catch (WebException ex)
    {
        throw ex;
    }       
    catch (Exception ex)
    {
        throw ex;
    }
});

Better: check if the task faulted before accessing task.Result:

var client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(...);
return client.GetStringAsync(url).ContinueWith(task =>
{
    if (task.IsFaulted)
    {
        var ex = task.Exception;
    }
    else if (task.IsCancelled)
    {
    }
    else
    {
        return task.Result;
    }
});

If you're not actually doing something in the ContinueWith, you can simply omit it:

var client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(...);
return client.GetStringAsync(url);
like image 90
dtb Avatar answered Oct 01 '22 05:10

dtb