gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 08:18:43 24 4
gpt4 key购买 nike

我有这样的方法:

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com