簡體   English   中英

有未處理的異常時如何確保記錄異常

[英]How to ensure log the exception when there is unhandled exception

我想要一個崩潰報告,因此我在App.xaml.cs中注冊了UnhandledException事件,如下所示。 但是有兩個問題:

  1. 有時,沒有異常的調用棧
  2. 有時,在進程終止之前,我沒有足夠的時間將日志寫入文件。

有什么建議嗎?

this.UnhandledException += App_UnhandledException;
private async void App_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
    if (!hasHandledUnhandledException)
    {
        e.Handled = true;
        _logger.Error("Unhandle exception - message = {0}\n StackTrace = {1}", e.Exception.Message, e.Exception.StackTrace);
        await CrashHandler.ReportExceptionAsync(e.Exception.Message, e.Exception.StackTrace);
        hasHandledUnhandledException = true;
        throw e.Exception;
    }
}

確保僅訪問e.Exception一次。 在某些情況下, 有關stacktrace的信息會在您第二次訪問該屬性時丟失 將異常保存在變量中,然后直接使用該變量。 另外,正如Panagiotis Kanavos在評論中提到的那樣,直接登錄e.Exception.ToString()以確保不丟失任何信息。 這將包括消息,調用堆棧和所有內部異常(您未在當前代碼中登錄)。

private async void App_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
    if (!hasHandledUnhandledException)
    {
        e.Handled = true;
        var exception = e.Exception;
        _logger.Error("Unhandled exception - {0}", exception);
        await CrashHandler.ReportExceptionAsync(exception.Message, exception.StackTrace);
        hasHandledUnhandledException = true;
        throw e.Exception;
    }
}

至於沒有足夠的時間來記錄異常的問題,它是由運行時控制的,因此您無能為力。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM