.NET 编写事件处理程序以捕获本地异常

.NET Write Event Handler to Catch Local Exception

我正在为用 VB.NET 编写的遗留代码库编写一个记录器,其中包含许多具有以下形式的事件和函数:

Try
    'Do some stuff here'
Catch ex As Exception
    'Handle the exception here'
EndTry

其中Try语句是方法的第一行,EndTry是方法的最后一行。因为代码多年来一直没有维护,所以没有人确定 try-catch 是否真的有必要。现在,我已经编写了一个挂钩到日志框架的单例 class,我可以这样称呼它:

With New MyLogger().Logger
    Try
        'Do some stuff here'
    Catch ex As Exception
        .Log("Some message", ex)
    EndTry
EndWith

其中 MyLogger 是用 .NET 4.0 编写的。我想在这里做的是删除内部 try-catch 并将其替换为 MyLogger 中的某个事件处理程序。我已经 AppDomain.CurrentDomain.UnhandledException 连接好了,但我的理解是事件只会引发异常,这些异常会一直通过应用程序而不会被捕获。是否有一个我可以处理的事件只会捕获使其进入对象更新所在的给定范围的异常?也许它看起来像这样:

public MyLogger()
{
    Something.CurrentScope.UnhandledException += MyHandler;
}

private MyHandler(object sender, UnhandledExceptionEventArgs args)
{
    // log the exception here
}

使用以下 VB.NET 代码:

With New MyLogger().Logger
    'Do some stuff here'
EndWith

任何帮助将不胜感激,谢谢!

基于更新问题的可能答案

看来您正在寻找范围本地处理程序,我很肯定没有这样的东西。

但是,您提交了:

With New MyLogger().Logger
    Try
        'Do some stuff here'
    Catch ex As Exception
        .Log("Some message", ex)
    EndTry
EndWith

通过适当的初始化,应该可以简化为:

With New MyLogger().Logger
    'Do some stuff here'
EndWith

我认为 lambda 包装器可以在此处帮助您:

本质上,您要做的不是 With Logger ... EndWith

MyLogger().DoWithCatch(
  Sub()
    ' Do some stuff here
  End Sub
)

其中 DoWithCatch 将像

一样实施
Sub DoWithCatch(ByVal lambda As Sub())
  Try
    lambda()
  Catch ex As Exception
    Log("Some message", ex)
  EndTry
End Sub

我想你明白了。

这样,您只需编写一次 catch 块。

我先说的

可能,您要找的是:AppDomain.FirstChanceException Event; docs

Provides data for the notification event that is raised when a managed exception first occurs, before the common language runtime begins searching for event handlers.


另一种成为所有异常的 "notified" 的全局方法是使用 Vectored Exception Handling。但这似乎只是不受管理的。

参考:Is it possible to do Vectored Strctured exception handling in c#?