c# - 记录从捕获异常的方法外部捕获的异常

标签 c# exception lambda

我有这样的方法:

public TResult DoSomethingWithLogging<TResult>(Func<TResult> someAction)
{
    try
    {
        return someAction.Invoke();
    }
    catch (Exception ex)
    {
        LogException(ex)
        throw;
    }

这个方法的用法如下:

var result = DoSomethingWithLogging(() => Foo());

我还想记录在 Foo() 中捕获的异常。我不能在 Foocatch 中使用 throw

如何捕获此类异常?

示例:

public static string Foo()
{
    try
    {
        return "Foo";
    }
    catch (Exception)
    {
        // I have to log this exception too without adding anything to Foo
        return "Exception caught";            
    }       
}

最佳答案

您可以绑定(bind)到 FirstChanceException 事件。这是您修改的代码以证明这一点:

using System;
using System.Runtime.ExceptionServices;

public class Program
{
  public static void Main()
  {
      AppDomain.CurrentDomain.FirstChanceException += 
      (object source, FirstChanceExceptionEventArgs e) =>
      {
        Console.WriteLine("FirstChanceException event raised in {0}: {1}",
          AppDomain.CurrentDomain.FriendlyName, e.Exception.Message);
      };
    Console.WriteLine("Hello World");
    Console.WriteLine(DoSomethingWithLogging(() => Foo()));
  }

  public static TResult DoSomethingWithLogging<TResult>(Func<TResult> someAction)
  {
    try
    {
      return someAction.Invoke();
    }
    catch (Exception ex)
    {
      Console.WriteLine(ex.Message);
      throw;
    }
  }

  public static string Foo()
  {
    try
    {
      throw new Exception("This will be caught");
      return"Foo";
    }
    catch (Exception) //I have to log this exception too without adding anything too Foo
    {
      return "Exception caught";      
    }    
  }
}

通常,除了调试场景之外,我会对此非常谨慎。一旦它被捕获,它就不应该被更高层的代码视为异常。 (当然,首先捕获它可能是一个逻辑错误,因此这在调试场景中确实具有一定的值(value))。

在多线程的情况下也有复杂的情况。上面的代码演示了 FirstChanceException 是如何工作的,但是如果您在调用之前附加并在调用之后分离,它仍然会被其他线程上的任何异常触发。过滤掉那些可能很棘手。我可能会首先考虑查看调用堆栈,但我不确定这是最好的方法。

关于c# - 记录从捕获异常的方法外部捕获的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33893220/

相关文章:

c++ - 完全作为库实现的 C++ is_lambda 特性是不可能的吗?

c# - SQL Visual Studio命令

c# - 如何在 WPF 中刷新/重新加载数据网格?

java - 抛出并捕获自定义异常

c++ - make_unique : Why is f(new T) exception safe 的异常安全

android - 更新到 Gradle 3.0.0-alpha1 时没有静态方法 lambda$onGoogleApiClientReady$0

c# - 正则表达式拆分字符串保留引号

C#/VB.NET : Howto improve anti-alias quality

java - 在 jtable 的自定义选项中编辑

java - 使用流 API 将 List<T> 转换为 Map<T.Prop, List<T>>