A global error handler for a class library in C#

我的梦境 提交于 2019-12-07 05:46:15

问题


Is there a way to catch and handle an exception for all exceptions thrown within any of the methods of a class library?

I can use a try catch construct within each method as in sample code below, but I was looking for a global error handler for a class library. The library could be used by ASP.Net or Winforms apps or another class library.

The benefit would be easier development, and no need to repeatedly do the same thing within each method.

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

回答1:


You can subscribe to global event handler like AppDomain.UnhandledException and check the method that throws exception:

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
    }
}


来源:https://stackoverflow.com/questions/17872620/a-global-error-handler-for-a-class-library-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!