如何在WinForms TraceListener中获取当前异常
时间:2020-03-06 14:23:33 来源:igfitidea点击:
我正在修改现有的WinForms应用程序,该应用程序使用自定义TraceListener设置,该应用程序记录了该应用程序中发生的所有未处理的错误。在我看来,TraceListener会获取异常的消息部分(即记录的内容),而不是其他异常信息。我希望能够获得异常对象(以获得stacktrace和其他信息)。
在我比较熟悉的ASP.NET中,我将调用Server.GetLastError来获取最新的异常,但当然在WinForms中将不起作用。
如何获得最近的异常?
解决方案
我假设我们已经设置了一个事件处理程序,以捕获未处理的域异常和线程异常。在该委托中,我们可能调用跟踪侦听器来记录异常。只需发出一个额外的调用来设置异常上下文。
[STAThread] private static void Main() { // Add the event handler for handling UI thread exceptions Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException); // Add the event handler for handling non-UI thread exceptions AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException); ... Application.Run(new Form1()); } private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) { MyTraceListener.Instance.ExceptionContext = e; Trace.WriteLine(e.ToString()); } private static void Application_ThreadException(object sender, ThreadExceptionEventArgs e) { // similar to above CurrentDomain_UnhandledException } ... Trace.Listeners.Add(MyTraceListener.Instance); ... class MyTraceListener : System.Diagnostics.TraceListener { ... public Object ExceptionContext { get; set; } public static MyTraceListener Instance { get { ... } } }
在MyTraceListener中的Write方法上,我们可以获取异常上下文并进行处理。记住要同步异常上下文。