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

Sco*_*ham 4 c# exception-handling

请考虑以下代码段:

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);
        }
Run Code Online (Sandbox Code Playgroud)

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

有没有一种方法可以聚合,同时仍然保留个别消息?

谢谢!

Ree*_*sey 5

有没有一种方法可以聚合,同时仍然保留个别消息?

是.该InnerExceptions属性将包括所有的例外,他们的消息.

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

try
{
    SomethingBad();
}
catch(AggregateException ae)
{
    foreach(var e in ae.InnerExceptions)
       Console.WriteLine(e.Message);
}
Run Code Online (Sandbox Code Playgroud)