Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling multiple exceptions in a loop

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?

like image 626
elolos Avatar asked Apr 22 '15 13:04

elolos


2 Answers

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)

like image 149
Habib Avatar answered Oct 13 '22 18:10

Habib


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.

like image 20
elolos Avatar answered Oct 13 '22 17:10

elolos