【问题标题】:A global error handler for a class library in C#C# 中类库的全局错误处理程序
【发布时间】:2013-07-26 04:59:30
【问题描述】:

有没有办法捕捉和处理在类库的任何方法中抛出的所有异常?

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

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

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

【问题讨论】:

  • 可以使用ContextBoundObject
  • 你能分享一些示例代码,但前提是你有它?谢谢

标签: c# error-handling class-library


【解决方案1】:

您可以订阅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
    }
}

【讨论】:

  • 只是好奇。这会在获取 exceptionObject.TargetSite.DeclaringType.Assembly 时涉及反射吗?
  • TargetSite属性返回MethodBase类型的方法,该方法抛出当前异常。 MethodBase 类型是反射库的一部分,因此将使用反射。
猜你喜欢
  • 2013-03-06
  • 2023-04-04
  • 1970-01-01
  • 2013-12-17
  • 2019-11-14
  • 1970-01-01
  • 2015-06-02
  • 2012-08-11
相关资源
最近更新 更多