如何获取导致exception的方法的名称

我的代码如下所示。

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

我需要一种方法来显示方法名称,假设在上面的例子中,如果在GetAllProductCategories()方法中抛出任何exception,我需要获取此方法名称,即“GetAllProductCategories()”作为我的结果。 谁能建议我怎么做?

System.Exception上有一个TargetSite属性应该派上用场。

获取抛出当前exception的方法。

在你的情况下,你可能想要这样的东西:

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

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

如果抛出此exception的方法不可用且堆栈跟踪不是空引用(在Visual Basic中为Nothing),则TargetSite从堆栈跟踪中获取方法。 如果堆栈跟踪是空引用,则TargetSite也返回空引用。

注意:如果exception处理程序跨应用程序域边界处理exception,则TargetSite属性可能无法准确报告引发exception的方法的名称。

您也可以像@leppie建议的那样使用StackTrace属性,但请注意这是堆栈上帧的字符串表示forms; 所以如果你只想要抛出execption的方法的名称 ,你将不得不操纵。

它在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处理程序类的编写不仅仅是记录exception,因此需要一个新的StackTrace对象。 显然,找到“抛出exception的方法”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处理程序中,exception对象不可用(即跟踪和审计),因此需要新的StackTrace()对象来检索最后执行的方法,即Logging方法之前的方法。

看看堆栈跟踪。

这是例外的财产。