[英]Catching all exception
我有一個項目可能會在任何函數和對象上拋出異常,有沒有辦法在整個框架/程序中捕獲任何和所有異常,以便我可以記錄它們,以便我以后可以看到它們? 我想要調用堆棧和異常消息。 我不一定知道異常將在哪里拋出,但我想記錄在程序的整個生命周期中發生的任何異常。 反正有沒有這樣做? 我不想嘗試並捕獲任何可能的異常拋出功能。 由於未處理的異常,程序將中斷,但我想先記錄它。
是的,有辦法做到這一點。 在主要部分寫下以下行:
// Add the event handler for handling UI thread exceptions to the event.
Application.ThreadException += new ThreadExceptionEventHandler(MainForm_UIThreadException);
// Set the unhandled exception mode to force all Windows Forms errors to go through
// our handler.
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
// Add the event handler for handling non-UI thread exceptions to the event.
AppDomain.CurrentDomain.UnhandledException +=
new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
而不是處理例外
private static void MainForm_UIThreadException(object sender, ThreadExceptionEventArgs t)
{
//do something
}
private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
//do something
}
捕獲異常的一個主要方面是根據拋出的異常類型正確處理它們。 通過擁有一個大的異常處理程序,您無法處理個別異常,而可能只是吞下它們。 但這並不是說在所有情況下都無法完成或不應該這樣做。
如果您的項目需要一個大處理程序,那么您可以簡單地處理AppDomain.UnhandledException事件。 即使您在其他地方捕獲異常,處理此方法也是一個好主意,以確保您的程序不會在錯過異常時拋出不友好的錯誤。 這假設您正在創建一個WinForm
。
由於您還在使用WCF
,因此可以查看IErrorHandler接口以幫助處理故障消息。
有沒有辦法在整個框架/程序中捕獲任何和所有異常,以便我可以記錄它們以便以后可以看到它們?
趕上了所有的應用程序類型的所有未處理的異常的唯一方法是使用已經提到AppDomain.CurrentDomain.UnhandledException
。 但是,你不能阻止你的應用程序終止使用該事件(嗯,你可以,但我不會告訴你如何,因為它是一種hackish)。
但是,在大多數框架中,有一些方法可以捕獲未處理的異常,這些異常允許您只是接受異常並繼續前進。 由於您提到了WCF,您可能想要閱讀有關IErrorHandler的內容
我不想嘗試並捕獲任何可能的異常拋出功能。
我就是這樣做的。 不要抓住那個例外 。 ;)
您可以在應用程序域級別捕獲異常 - App Domain Exception
AppDomain currentDomain = AppDomain.CurrentDomain;
currentDomain.UnhandledException += new UnhandledExceptionEventHandler(MyHandler);
如果您閱讀該鏈接,則會提到某些其他事件可能導致應用程序域無法觸發 - 例如ThreadException - 因此可能需要多個處理程序。
Application.ThreadException += new ThreadExceptionEventHandler (ThreadExceptionHandler);
並注意以下內容:(與winforms相關 - SetUnhandledExceptionMode )
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
您始終可以使用AppDomain.UnhandledException
static void Main()
{
AppDomain currentDomain = AppDomain.CurrentDomain;
currentDomain.UnhandledException += new UnhandledExceptionEventHandler(AppDomain_UnhandledException);
}
private static void AppDomain_UnhandledException(object sender, UnhandledExceptionEventArgs args) {
Logger.Log((Exception)args.ExceptionObject);
}
有沒有辦法在整個框架/程序中捕獲任何和所有異常,以便我可以記錄它們,以便我以后可以看到它們?
是的 ,桌面應用程序或Web應用程序有處理程序來處理未處理的異常。 在桌面應用程序中,該事件稱為UnhandledException。 在Web應用程序中,它是應用程序入口點上的Application_Error(通常是Global.asax.cs)。
我不想嘗試並捕獲任何可能的異常拋出功能。 由於未處理的異常,程序將中斷,但我想先記錄它。
如果您不想捕獲異常,您可以隨時簡單地重新拋出。 它會繼續冒泡而導致程序崩潰。
catch(Exception ex)
{
//logging here
throw;//rethrow
}
我想要調用堆棧和異常消息。
Exception
類包含這些。 在事件處理程序的情況下,有多種方法可以訪問,具體取決於它的應用程序類型。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.