2015-11-04 68 views
1

我有一個方法提供了一個Exception對象,我想記錄一個錯誤,如果在錯誤處理程序本身發生任何事情。下面是一些僞代碼:C# - 創建新的異常而不丟失堆棧跟蹤和內部異常?

public override void OnError(Exception originalException) 
{ 
    try 
    { 
     // Do work... 
    } 
    catch (Exception e) 
    { 
     // How do I create this exception without losing the stack 
     // trace of e and preserving any inner exceptions that were 
     // in e at the same time including the details of 
     // originalException? 
     Exception newException = new Exception(e.Message, originalException); 
     Logger.Error("An error occurred", newException); 
    } 
} 

基本上,我試圖originalException和e以上組合到一個異常消息傳遞給一個記錄器對象。我想一個選擇是創建2個單獨的日誌消息,但它不是理想的。

+0

那麼你爲什麼不採取原來的例外只......?那麼不需要再創建一個新的異常。 – User2012384

+0

我也想記錄錯誤過濾器本身發生了什麼。 – Andrew

+0

'originalException'可通過'newException'的'InnerException'屬性訪問 - 你可以看看InnerException的堆棧跟蹤。否則,你唯一的選擇是重新拋出原始異常:'try {...} catch(ex){Logger.Error(ex);扔; }' – Serguei

回答

0

你可以使用一個AggregateException包多個異常:

public override void OnError(Exception originalException) 
{ 
    try 
    { 
     // Do work... 
    } 
    catch (Exception e) 
    { 
     var exs = new AggregateException(originalException, e); 
     Logger.Error("An error occurred", exs); 
    } 
} 

編輯:如果Logger不記錄InnerException屬性(或InnerExceptions在這種情況下)的內容,則似乎是唯一的選擇就是多次調用Logger.Error