处理多个 http 请求异步与错误处理的正确方法



该解决方案有效,但是有没有更好的方法来处理这样的多个请求。

下面的代码描述了我想做什么,并且绝对有效。但我相信有更好的方法来解决这个问题吗?我也尝试了其他选项,但它失败了,因为某些请求将返回 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;
}

您可能正在处理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);
    }
}

最新更新