有没有一种方法可以捕获和处理在类库的任何方法中抛出的所有异常?
我可以在每个方法中使用 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/