Csharp/C#教程:C#中是否存在集中式error handling流程分享


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()); } 

使用AppDomainUnhandledException事件:

  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用法。

上述就是C#学习教程:C#中是否存在集中式error handling流程分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请点击右边联系管理员删除。

如若转载,请注明出处:https://www.ctvol.com/cdevelopment/1002601.html

(0)
上一篇 2021年12月28日
下一篇 2021年12月28日

精彩推荐