c# - C# 中类库的全局错误处理程序

标签 c# error-handling class-library

有没有一种方法可以捕获和处理在类库的任何方法中抛出的所有异常?

我可以在每个方法中使用 try catch 构造,如下面的示例代码所示,但我一直在寻找类库的全局错误处理程序。该库可由 ASP.Net 或 Winforms 应用程序或其他类库使用。

好处是更容易开发,并且不需要在每个方法中重复做同样的事情。

public void RegisterEmployee(int employeeId)
{
   try
   {
     ....
   }
   catch(Exception ex)
   {
     ABC.Logger.Log(ex);
   throw;
   }
}  

最佳答案

您可以订阅全局事件处理程序,如 AppDomain.UnhandledException 并检查抛出异常的方法:

AppDomain.CurrentDomain.UnhandledException += CurrentDomainOnUnhandledException;

private static void CurrentDomainOnUnhandledException(object sender, UnhandledExceptionEventArgs unhandledExceptionEventArgs)
{
    var exceptionObject = unhandledExceptionEventArgs.ExceptionObject as Exception;
    if (exceptionObject == null) return;
    var assembly = exceptionObject.TargetSite.DeclaringType.Assembly;
    if (assembly == //your code)
    {
        //Do something
    }
}

关于c# - C# 中类库的全局错误处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17872620/

相关文章:

c# - Outlook 2010 VSTO - 窗体区域中的标准 Office 图标

c# - 如何确保 ViewModel 属性在再次更改其值之前已绑定(bind)在 View 上?

javascript - 异步加载谷歌地图时快速失败

jsf-2 - 从 Facelets 错误页面引用 CDI 托管 bean

error-handling - 源数据为空且目标列不可为OLDEDBDestination任务时,SSIS未记录错误

language-agnostic - 最好的图书馆做网络抓取

c# - 无法使用 ServiceController 启动和停止服务

c# - 如何在 asp.net 中扩展用户控件?

c# - 每次页面加载时都会触发按钮的 OnClick 事件