2013-11-26 22 views
1

我正在實施ConvertDocuments()API。這個API獲取一組輸入文件並將每個文件轉換爲另一種文件格式。如果任何文檔無法轉換(可能是損壞的文件),我不想通過引發異常來關閉整個轉換作業。我在我的類(ConverterError事件)上使用該用戶可以獲取錯誤信息的事件處理程序。爲了給出關於錯誤的完整細節,我還在事件參數中包含了異常對象。我想知道是否有任何缺點,如果我遵循這種模式。在事件中提供異常對象

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} 
    } 
} 

回答

2

我看不到這種做法的特殊問題,但你可能看而不是在所有的異常捆綁成一個AggregateException和一次性返回它們。

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

更新:

下面就來介紹這種使用AggregateException的文章,這可能會感興趣的鏈接:http://richhewlett.com/2010/05/12/raising-multiple-exceptions-with-aggregateexception/

+0

好方法整理所有的異常,直到結束然後把它們放在一起。但對於我的要求,我還必須返回已轉換文檔的列表。如果我在最後拋出AggregateException,那將意味着操作不成功。我接受這一點,因爲它對許多其他情況很有幫助。 – Algorist