C # cumulative exceptions not storing individual exception messages

Consider the following code snippet:

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 is a list of exceptions that I am adding. When the loop is finished, I then take this list and add it to the AggregateException, and then throw it. When I run the debugger, each of the string messages "Setting X is required" appears in the catExceptions collection. However, when it comes to AggregateException, the only message is now "One or more errors occurred."

Is there a way I can combine when saving individual posts?

Thanks!

+4
source share
2 answers

Is there a way I can combine when saving individual posts?

Yes. The InnerExceptions property will include all exceptions with their messages.

You can display them if necessary. For instance:

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

However, the poster described above gave the correct answer; instead of using the foreach loop, you can use the .handle() method.

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

All Articles