【发布时间】:2021-11-21 18:17:36
【问题描述】:
动物名称是从 API 中获取的,如果找不到动物,该 API 可能会返回 404。但为了正确记录错误,我们需要访问动物所在的国家/地区。可能吗?我读过something from a guy called Stephen Cleary,这让我觉得 lambdas 是可能的,但我找不到任何东西。
var gettingNames = new List<Task<string>>();
foreach (var animal in animals)
{
gettingNames.Add(this.zooApi.GetNameAsync(animal));
}
try
{
await Task.WhenAll(gettingNames);
}
catch (Exception e)
{
var exception = gettingNames.Where(task => task.IsFaulted)
.SelectMany(x => x.Exception.InnerExceptions).First();
this.logger.LogError("The animal name from {Country} was not found",
animal.Country); // This is the goal
}
【问题讨论】:
-
您需要一种方法将错误任务转换回引发其创建的动物。您可能希望创建一个从任务对象到动物的字典映射,以用于您的异常处理。
-
你的意思是@StephenCleary? stackoverflow.com/users/263693/stephen-cleary :)
标签: c# exception async-await task-parallel-library