解包异常堆栈

时间:2014-04-21 19:06:42

标签: c# .net

在我的代码中,我有一个记录错误的通用方法,类似这样的

static void LogError(Exception ex, string methodName)
{
    // the actual logging is much more complex
    Console.WriteLine(methodName);
    Console.WriteLine(ex);
}

现在,在每种方法中我都必须以这种形式使用try / catch

static void TestMethod1()
{
    try
    {
        // do the actual operation here
        string s = null;

        s = s.Substring(1);
    }
    catch (Exception exec)
    {
        LogError(exec, System.Reflection.MethodBase.GetCurrentMethod().Name);
    }
}

如果发生异常,记录的信息将显示确切的方法名称TestMethod1

虽然这项工作我不喜欢将try / catch添加到每个方法,所以我想写这样的替换

static void DoWithLog(Action a)
{
    try
    {
        a();
    }
    catch (Exception ex)
    {
        LogError(ex, System.Reflection.MethodBase.GetCurrentMethod().Name);
    }
}

private static void TestMethod2()
{
    DoWithLog(() =>
        {
            string s = null;

            s = s.Substring(1);
        });
}

这种方式在我的方法中我实际上用try / catch编写了所需的代码。虽然这是按预期工作的,但我不再获得原始方法名称,我得到了lambda名称。有没有办法从异常堆栈跟踪原始方法名称TestMethod2

P.S。我知道将一切都包含在try / catch中是不好的,并且必须使用全局异常处理程序,但是这个项目在我之前写的很多,没有人愿意改变它。

1 个答案:

答案 0 :(得分:1)

这应该有用。

StackTrace stackTrace = new StackTrace();
MethodBase methodBase = stackTrace.GetFrame(1).GetMethod();
Console.WriteLine(methodBase.Name);

取自类似问题:

Retrieving the calling method name from within a method