HttpClient - dealing with aggregate exceptions

后端 未结 1 1377
逝去的感伤
逝去的感伤 2021-02-01 09:29

Hi i am using HttpClient similar to this:

public static Task AsyncStringRequest(string url, string contentType)
{
    try
    {
        var client          


        
相关标签:
1条回答
  • 2021-02-01 10:09

    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);
    
    0 讨论(0)
提交回复
热议问题