在 c# 中聚合异常,不保存单个异常消息

本文关键字:异常 保存 单个 消息 | 更新日期: 2023-09-27 18:37:00

请考虑以下代码片段:

foreach (var setting in RequiredSettings)
                {
                    try
                    {
                        if (!BankSettings.Contains(setting))
                        {
                            throw new Exception("Setting " + setting + " is required.");
                        }
                    }
                    catch (Exception e)
                    {
                        catExceptions.Add(e);
                    }
                }
            }
            if (catExceptions.Any())
            {
                throw new AggregateException(catExceptions);
            }
        }
        catch (Exception e)
        {
            BankSettingExceptions.Add(e);
        }
        if (BankSettingExceptions.Any())
        {
            throw new AggregateException(BankSettingExceptions);
        }

catExceptions 是我添加的异常列表。 循环完成后,我获取该列表并将它们添加到 AggregateException 中,然后抛出它。 当我运行调试器时,每个字符串消息"需要设置 X"都出现在 catExceptions 集合中。 但是,当涉及到 AggregateException 时,现在唯一的消息是"发生了一个或多个错误"。

有没有办法在保留单个消息的同时进行聚合?

谢谢!

在 c# 中聚合异常,不保存单个异常消息

有没有办法在保留单个消息的同时进行聚合?

是的。 属性将包括所有异常及其消息。

您可以根据需要显示这些内容。 例如:

try
{
    SomethingBad();
}
catch(AggregateException ae)
{
    foreach(var e in ae.InnerExceptions)
       Console.WriteLine(e.Message);
}

上面的海报给出了正确的答案,但是,可以使用.handle()方法,而不是使用 foreach 循环。

try
{
    SomethingBad();
}
catch(AggregateException ae)
{
    ae.handle(x => {
        Console.WriteLine(x.Message);
        return true;
    });
}