![](/img/trans.png)
[英]How to rethrow the inner exception of a TargetInvocationException without losing the stack trace
[英]C# - Create new exception without losing stack trace and inner exceptions?
我有一個提供Exception對象的方法,並且如果錯誤處理程序本身發生任何事情,我想記錄一個錯誤。 這是一些偽代碼:
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合並為一個Exception消息,以傳遞給logger對象。 我想一個選擇是創建2條單獨的日志消息,但這並不理想。
您可以使用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
多次調用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.