2008-09-18 3 views
1

응용 프로그램에서 발생하는 모든 처리되지 않은 오류를 기록하는 사용자 지정 TraceListener로 설정된 기존 WinForms 응용 프로그램을 수정하려고합니다. TraceListener가 (예외가 기록되는) 예외의 메시지 부분을 가져 오는 것처럼 보이지만 다른 예외 정보는 나타나지 않는 것 같습니다. stacktrace 및 기타 정보를 얻으려면 예외 개체를 얻을 수 싶습니다.WinForms TraceListener에서 현재 예외를 얻는 방법

더 익숙한 ASP.NET에서는 가장 최근의 예외를 얻기 위해 Server.GetLastError를 호출하지만 물론 WinForms에서는 작동하지 않습니다.

어떻게하면 가장 최근의 예외를 얻을 수 있습니까?

답변

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의 쓰기 메서드에서 예외 컨텍스트를 가져와 작업 할 수 있습니다. 예외 상황을 동기화하는 것을 잊지 마십시오.

관련 문제