如何获取导致异常的方法的名称

时间:2011-01-04 20:48:40

标签: c# exception-handling try-catch

我的代码如下所示。

try
{
    _productRepo.GetAllProductCategories();
}
catch (Exception ex)
{
    //Do Something
}

我需要一种方法来显示方法名称,假设在上述情况下如果在GetAllProductCategories()方法中抛出任何异常,我需要获取此方法名称,即" GetAllProductCategories()"作为我的结果。谁能建议我怎么做?

3 个答案:

答案 0 :(得分:21)

System.Exception上的TargetSite属性应该派上用场。

  

获取抛出的方法   目前的例外。

在您的情况下,您可能需要以下内容:

catch (Exception ex)
{
   MethodBase site = ex.TargetSite;
   string methodName = site == null ? null : site.Name;
   ...           
}

值得指出列出的一些问题:

  

如果抛出此方法   异常不可用而且   堆栈跟踪不是空引用   (在Visual Basic中没有任何内容),TargetSite   从堆栈中获取方法   跟踪。如果堆栈跟踪为null   参考,TargetSite也返回一个   null reference。

     

注意:TargetSite属性可能不会   准确报告名称   异常的方法   如果异常处理程序抛出   处理异常   应用领域边界。

您可以使用StackTrace属性,如@leppie所建议的那样,但要注意这是堆栈上帧的字符串表示形式;因此,如果您只想要抛出该执行的方法的名称,则必须进行操作。

答案 1 :(得分:3)

它在StackFrame中......

private string GetExecutingMethodName()
{
    string result = "Unknown";
    StackTrace trace = new StackTrace(false);
    Type type = this.GetType();

    for (int index = 0; index < trace.FrameCount; ++index)
    {
        StackFrame frame = trace.GetFrame(index);
        MethodBase method = frame.GetMethod();

        if (method.DeclaringType != type && !type.IsAssignableFrom(method.DeclaringType))
        {
            result = string.Concat(method.DeclaringType.FullName, ".", method.Name);
            break;
        }
    }

    return result;
}

此方法是为Logging处理程序类编写的,使用GetType()只是消除了Logging处理程序类中的方法作为最后执行的方法返回。由于Logging处理程序类的编写不仅仅是记录异常,因此需要一个新的StackTrace对象。显然,找到“抛出异常的方法”可能没有必要使用GetType()。

如果您只想要堆栈顶部,请选择第一帧,调用GetMethod()并返回,或者只使用TargetSite。然后可以删除GetType()。另请注意,需要传入Exception来创建StackTrace对象。例如:

class Program
{
    static void Main(string[] args)
    {
        try
        {
            Test();
        }
        catch (Exception ex)
        {

            // does not work properly - writes "Main"
            Console.WriteLine(MethodBase.GetCurrentMethod());

            // properly writes "TestConsole.Program.Test"
            Console.WriteLine(GetExecutingMethodName(ex));

            // properly writes "Test"
            Console.WriteLine(ex.TargetSite.Name);
        }

        Console.ReadKey();
    }


    static void Test()
    {
        throw new Exception("test");
    }

    private static string GetExecutingMethodName(Exception exception)
    {
        var trace = new StackTrace(exception);
        var frame = trace.GetFrame(0);
        var method = frame.GetMethod();

        return string.Concat(method.DeclaringType.FullName, ".", method.Name);
    }
}

基本上,如果TargetSite()做你想要的,那就不要再继续了。但是,通常在Logging处理程序中,异常对象不可用(即跟踪和审计),因此需要一个新的StackTrace()对象来检索最后执行的方法,即Logging方法之前的方法。

答案 2 :(得分:1)

查看堆栈跟踪。

这是异常的属性。