C#中是否存在集中式error handling流程
有没有办法集中error handling或exception处理而不使用try catch方法?
如果这是用于ASP.NET,您可以将Global.asax
文件添加到网站并处理Application_Error
方法。
这就是我通常使用它的方式:
void Application_Error(object sender, EventArgs e) { // Code that runs when an unhandled error occurs if (!System.Diagnostics.EventLog.SourceExists("MySource")) { System.Diagnostics.EventLog.CreateEventSource("MySource", "Application"); } System.Diagnostics.EventLog.WriteEntry("MySource", Server.GetLastError().ToString()); }
使用AppDomain
的UnhandledException
事件:
static void Main(string[] args) { AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException); } static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) { // log the exception }
对于ASP.NET使用,您将使用glabal.asax。
您可以尝试使用基于AOP的插件(如PostSharp)将exception处理代码注入您的类和/或具有自定义属性的方法。 这是在编译后完成的,因此您的源代码保持干净。 看看这个 – http://www.sharpcrafters.com/postsharp/documentation/getting-started
如果您使用的是WinForms,您可以查看我的其他相关答案 。 它确实使用了try-catch
,因为没有其他方法我知道。
请参阅ASP.NET的其他答案和其他可能的.NET用法。