Inherit异常类记录所有后续的异常事件 [英] Inherit Exception class to log all subsequent occurrences of exception
问题描述
如果我想在我的应用程序中记录所有出现的异常,
If I want to log all occurrences of exceptions throughout my application so far,
我应该继承Exception类并抛出该类的所有异常,
should I inherit Exception class and throw all exception of that class,
其构造函数将记录错误详细信息。
whose constructor will log the error details..
或任何想法或建议?
推荐答案
根据应用程序的类型(ASP.NET/Console等),有不同的方法。
Depending on the type of Application (ASP.NET/Console etc) there are different approaches to take.
对于Windows Forms应用程序,这是可以去的: -
For Windows Forms Applications this is the way to go: -
namespace YourNamespace
{
static class Program
{
[STAThread]
static void Main()
{
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
{
HandleException(e.Exception);
}
static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
HandleException((Exception)e.ExceptionObject);
}
static void HandleException(Exception e)
{
//Handle the Exception here
}
}
}
在ASP.NET中,您可以通过使用Application_OnError事件捕获所有未处理的异常Global.asax或通过挂钩到具有您自己的HttpModule的Application.OnError事件。
In ASP.NET you can capture all Unhandled Exceptions by using the Application_OnError event within the Global.asax or by hooking up to the Application.OnError event with your own HttpModule.
您还可以使用其中一个第三方异常处理程序。
You can also use one of these third party exception handlers.
ELMAH支持ASP.NET应用程序
ELMAH supports ASP.NET Applications
http://code.google.com/p/elmah/
Exceptioneer(我们构建 - 只是标记我对该地区的兴趣)支持ASP.NET,控制台应用程序,Windows窗体应用程序,WPF应用程序等。
Exceptioneer (We build this - just flagging up my interest in the area) supports ASP.NET, Console Applications, Windows Forms Appliactions, WPF Applications etc.
这篇关于Inherit异常类记录所有后续的异常事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!