1

アプリで発生した未処理のエラーをログに記録するカスタム TraceListener でセットアップされた既存の WinForms アプリを変更しています。TraceListener が例外のメッセージ部分 (ログに記録されるもの) を取得するように思えますが、他の例外情報は取得しません。例外オブジェクトを取得できるようにしたいと思います(スタックトレースやその他の情報を取得するため)。

私がよく知っている ASP.NET では、Server.GetLastError を呼び出して最新の例外を取得しますが、もちろん WinForms では機能しません。

最新の例外を取得するにはどうすればよいですか?

4

1 に答える 1

3

未処理のドメイン例外とスレッド例外をキャッチするイベント ハンドラーを設定したとします。そのデリゲートでは、おそらくトレース リスナーを呼び出して例外をログに記録します。例外コンテキストを設定するには、追加の呼び出しを発行するだけです。

[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 メソッドで、例外コンテキストを取得して操作できます。例外コンテキストを同期することを忘れないでください。

于 2008-09-18T23:59:29.343 に答える