HttpClient - dealing with aggregate exceptions

泄露秘密 提交于 2019-12-03 05:11:33

问题


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?


回答1:


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);


来源:https://stackoverflow.com/questions/11239537/httpclient-dealing-with-aggregate-exceptions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!