C#中类库的全局错误处理程序 [英] A global error handler for a class library in C#

查看:77
本文介绍了C#中类库的全局错误处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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


推荐答案

您可以订阅 AppDomain.UnhandledException 这样的全局事件处理程序,并检查引发异常的方法:

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

这篇关于C#中类库的全局错误处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆