[英]How to ensure log the exception when there is unhandled exception
I want a crash reporting, so I register the UnhandledException event in App.xaml.cs like following. 我想要一个崩溃报告,因此我在App.xaml.cs中注册了UnhandledException事件,如下所示。 But there are 2 problems:
但是有两个问题:
Any advice? 有什么建议吗?
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;
}
}
Make sure to access e.Exception
only once. 确保仅访问
e.Exception
一次。 In some cases, information about the stacktrace is lost the second time you access the property . 在某些情况下, 有关stacktrace的信息会在您第二次访问该属性时丢失 。 Save the exception in a variable and work directly with that variable.
将异常保存在变量中,然后直接使用该变量。 Also, as mentioned by Panagiotis Kanavos in the comments, directly log
e.Exception.ToString()
to make sure to miss no information. 另外,正如Panagiotis Kanavos在评论中提到的那样,直接登录
e.Exception.ToString()
以确保不丢失任何信息。 This will include the message, the callstack, and all inner exceptions (which you are not logging in your current code). 这将包括消息,调用堆栈和所有内部异常(您未在当前代码中登录)。
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;
}
}
As for the problem of not having enough time to log the exception, it's controlled by the runtime so you can't do anything about it. 至于没有足够的时间来记录异常的问题,它是由运行时控制的,因此您无能为力。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.