正确处理多种HTTP请求异步的错误处理方法

时间:2019-04-12 12:57:32

标签: c# rest http async-await

该解决方案有效,但是有一种更好的方式通过错误处理来处理多个请求。

下面的代码描述了我想做什么,并且绝对有效。但是我敢肯定有更好的方法来解决这个问题? 我也尝试过其他选项,但由于某些请求将返回404,因此失败。

public async Task<List<Bruker>> TryGetContactsByContactIds(List<AZContact> contacts)
{
    var tasks = contacts.Select(c => TryGetContactAsync(c.Email)).Where(c => c.Result != null);

    try
    {
        var tasksresult = await Task.WhenAll(tasks);
        return tasksresult.ToList();
    }
    catch (Exception e)
    {
        _logger.Error("unable to fetch all", e);
    }


    return new List<Bruker>();
}

public async Task<Bruker> TryGetContactAsync(string userId)
{
    try
    {
        var user = await _brukereClient.GetAsync(userId);
        return user;
    }
    catch (SwaggerException e)
    {
        if (e.StatusCode == 404)
        {
            _logger.Info($"user with Id {userId} does not exist");
        }
        else
        {
            _logger.Error("Unable to fetch user", e);
        }
    }

    return null;
}

1 个答案:

答案 0 :(得分:-1)

您可能正在处理await的功能/限制,该功能/限制仅引发已等待任务(在这种情况下为WhenAll任务)的聚合异常之一。您必须枚举所有任务来处理每个单独的异常。

try
{
    var tasksresult = await Task.WhenAll(tasks);
    return tasksresult.ToList();
}
catch (Exception e)
{
    foreach (var task in tasks)
    {
        if (task.IsFaulted)
        {
            var taskException = task.Exception.InnerException;
            // ^^ Assuming that each task cannot have more than one exception inside its AggregateException.
            if (taskException is SwaggerException swaggerException)
            {
                if (swaggerException.StatusCode == 404)
                {
                    _logger.Info($"user with Id {userId} does not exist");
                }
                else
                {
                    _logger.Error("Unable to fetch user", swaggerException);
                }
            }
            else
            {
                _logger.Error("An unexpected task error occurred", taskException);
            }
        }
    }
    if (!tasks.Any(t => t.IsFaulted))
    {
        _logger.Error("A non task-related error occurred", e);
    }
}