为什么 UnhandledExceptionEventArgs.Exception return 有用的信息只在第一次访问时出现?

Why does UnhandledExceptionEventArgs.Exception return useful info only on first access?

App.UnhandledException 中,当第一次访问 e.Exception 时,它 returns 消息和堆栈跟踪如预期的那样。再次访问它时,它只会 returns 消息 "Exception of type 'System.Exception' was thrown."

这是错误还是这里发生了什么?

示例:

Private Sub App_UnhandledException(sender As Object, e As UnhandledExceptionEventArgs) Handles Me.UnhandledException
  Dim ex1 = e.Exception
  Debug.WriteLine($"ex1={ex1}")
  Dim ex2 = e.Exception
  Debug.WriteLine($"ex2={ex2}")
End Sub

抛出 New MyCustomException($"Testing app crash.") 结果:

ex1=ErrorHandlingDemo.MyCustomException: Testing app crash. 
   at ErrorHandlingDemo.MainPage.btnForceUnhandledEx_Click(Object sender, RoutedEventArgs e)
   at Windows.ApplicationModel.Core.UnhandledError.Propagate()
   at ...

ex2=System.Exception: Exception of type 'System.Exception' was thrown.

我知道 e.Message 确实保存了原始消息(并且在调试中构建了堆栈跟踪的一部分)。 e.Exception 仅在首次访问时返回有价值的信息的行为仍然看起来很奇怪。

作为解决方法,我先将其分配给一个局部变量,然后再使用它。

Dim ex = e.Exception
Trace(ex)
If Typeof(ex) is MyCustomException
...

即使使用这种解决方法,也必须小心:在赋值之前设置断点(这会导致调试器访问 e.Exception)会破坏原始值。

sample code.

这是一个非常令人困惑的行为,尤其是因为即使简单地设置断点也会破坏 UnhandledExceptionEventArgs.Exception 的原始值。 MS 应该改变这种行为或至少记录它。

通过将 ex.Exception 分配给局部变量的解决方法,可以使用以下异常详细信息:

有关在 UWP-Apps 中处理意外异常的更多想法,我的博客 post Global Error Handling for UWP-Apps 可能会有所帮助。