michasaucer
michasaucer

Reputation: 5228

Own Exception with IEnumerable<Exception>

I Want to make my own exception like AggregateException :

var exceptions = ErrorCollectionExtension.GetErrorsAsExceptions(compiler.Errors);
throw new AggregateException("Error", exceptions);

that can take as param List of Exceptions:

public MyException(string message, IEnumerable<Exception> innerExceptions)
        : base(message, innerExceptions)
    {

    }

But i get an error on innerExceptions in base.

How to make own exception with collection of it like AggregateException?

Upvotes: 1

Views: 134

Answers (1)

Raul
Raul

Reputation: 3131

One way would be to simply extend the Exception class by a collection of inner exceptions, somewhat like this:

public class MyException : Exception
{
    private readonly ReadOnlyCollection<Exception> _innerExceptions;

    public MyException(string message, IEnumerable<Exception> innerExceptions)
        : base(message, innerExceptions.FirstOrDefault())
    {
        _innerExceptions = innerExceptions.ToList().AsReadOnly();
    }

    public ReadOnlyCollection<Exception> InnerExceptions => _innerExceptions;
}

Alternatively you can just inherit from AggregateException and use its structure:

public class MyException : AggregateException
{

    public MyException(string message, IEnumerable<Exception> innerExceptions)
        : base(message, innerExceptions)
    {
    }
}

Upvotes: 2

Related Questions