In my code, a method is being called repeatedly within a loop like so:
foreach (var file in files)
{
SomeMethod(file);
}
The method is likely to throw exceptions, but I don't want the code to exit the loop after the first exception.
Furthermore, the code above is being called from a web api controller, so I need a way to pass all the exception information back to the controller, where it will be handled (log exception and return error response to the client).
What I've done so far is catch and store all the exception in a list.
var errors = new List<Exception>();
foreach (var file in files)
{
try
{
SomeMethod(file);
}
catch(Exception ex)
{
errors.Add(ex);
}
}
Considering that rethrowing all the errors in the list is not an option, what is the best approach to return the exception information to the controller?
Use AggregateException
.
You can pass the List<Exception>
to its constructor and throw that.
At the end of your loop do:
AggregateException aggregateEx = new AggregateException(errors);
throw aggregateEx;
(or return AggregateException
)
Based on Habib's suggestion, I've implemented a solution that also handles the case where there is just one exception. This way there are no unnecessarily nested exceptions.
if (errors.Any())
{
if (errors.Count > 1)
{
throw new AggregateException("Multiple errors. See InnerExceptions for more details",errors);
}
else
{
ExceptionDispatchInfo.Capture(errors[0]).Throw();
}
}
Simply rethrowing the single exception by calling throw errors[0];
should be avoided as it wouldn't preserve the stack trace of the original exception.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With