HttpClient - dealing with aggregate exceptions

瘦欲@ 提交于 2019-12-02 18:27:47
dtb

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