Algorist
Algorist

Reputation: 492

Providing exception object in events

I am implementing ConvertDocuments() API. This API takes set of input files and convert each file to another file format. If any document fails to get converted (may be a corrupted file) I don't want to close the entire Convert job by raising an exception. I have an event handler on my class (ConverterError event) using that user can get the error information. To give complete details on the error I am also including exception object in the event arguments. I would like to know if there is any drawback if I follow this pattern.

ConvertDocuments(List<string> InputDocsList, ...)
{
    foreach(file in InputDocsList)
    {
        try
        {
            Convert(file);
        }
        catch(exception ex)
        {
            OnConverterError(new ConverterErrorEventArgs(ex.Message, ex));
        }
    } 
}

OnConverterError(ConverterErrorEventArgs e)
{    
    EventHandler<ConverterErrorEventArgs> handler = ConverterError;
    if (handler != null)
    {
        handler(this, e);
    }
}

class ConverterErrorEventArgs: EventArgs
{

    ConverterErrorEventArgs(string message, Exception innerException)
    {
    ...
    }
    string Message
    {
        get{...}
    }
    Exception InnerException
    {
        get{return innerException}
    }
}

Upvotes: 1

Views: 62

Answers (1)

Will Dean
Will Dean

Reputation: 39500

I can't see any particular problem with that approach, but you might look instead at bundling up all the exceptions into an AggregateException and returning them in one lump.

http://msdn.microsoft.com/en-us/library/system.aggregateexception(v=vs.110).aspx

Update:

Here's a link to an article describing this sort of use of AggregateException, which might be of interest: http://richhewlett.com/2010/05/12/raising-multiple-exceptions-with-aggregateexception/

Upvotes: 2

Related Questions