2010-11-29 84 views
5

我需要重新拋出被捕獲並存儲在其他地方的異常沒有丟失有關何時第一次捕獲/存儲異常的堆棧跟蹤信息。我的代碼看起來是這樣的:在Silverlight中重新拋出異常時保留堆棧跟蹤

public void Test() 
    { 
     int someParameter = 12; 
     ExecuteSomeAsyncMethod(someParameter, CallbackMethod); 
    } 

    public void CallbackMethod(object result, Exception error) 
    { 
     //Check for exceptions that were previously caught and passed to us 
     if(error != null) 
      //Throwing like this will lose the stack trace already in Exception 
      //We'd like to be able to rethrow it without overwriting the stack trace 
      throw error; 

     //Success case: Process 'result'...etc... 
    } 

我已經看到了使用反射(例如herehere)對這個問題的解決方案,或者使用序列化(例如here),但這些都不將在Silverlight爲我工作(不允許使用私人反射,並且Silverlight中不存在序列化方法中使用的類/方法)。

有什麼辦法來保存在Silverlight中工作的堆棧跟蹤?

回答

3

拋出一個新異常,異常的內部異常:

throw new ApplcationException("Error message", error); 

內部異常將保留它的堆棧跟蹤。

+0

這看起來像我現在唯一的選擇。不幸的是,這可能會干擾現有的代碼,比如「catch(SpecificExceptionClass)」,否則它會檢查異常類型。理想情況下,我希望儘可能避免包裝Exception,因爲我不希望消費者必須開始檢查InnerExceptions是否存在「真實」異常。 – 2010-11-29 23:26:05

3

您可以使用

catch(Exeption) 
{ 
    throw; 
} 

catch(Exception e) 
{ 
    throw new Exception(e); 
} 

雙方將保持堆棧跟蹤。第一種解決方案在您的示例中似乎不可行,但第二種解決方案應該可行。

因爲你的情況,你會拋出參數error而不是e

+0

如果你想提及在這裏不起作用的每一種可能的解決方案,你忘了最簡單的解決方案:根本就沒有發現異常。 ;) – Guffa 2010-11-29 23:24:35

相關問題