问题描述
我的代码如下所示。
try
{
_productRepo.GetAllProductCategories();
}
catch (Exception ex)
{
//Do Something
}
我需要一种方法来显示方法名称,假设在上述情况下,如果在GetAllProductCategories()方法中抛出任何异常,我需要获取此方法名称即GetAllProductCategories() 作为我的结果。任何人都可以建议我怎么做?
I need a way to show the method name, suppose in the above case if any exception is thrown in the GetAllProductCategories() method, I need to get this method name i.e. "GetAllProductCategories()" as my result. Can any one suggest me how to do this?
推荐答案
有一个 TargetSite
一个>属性 System.Exception
,应该派上用场。
There's a TargetSite
property on System.Exception
that should come in handy.
在你的情况下,你可能需要这样的东西:
In your case, you probably want something like:
catch (Exception ex)
{
MethodBase site = ex.TargetSite;
string methodName = site == null ? null : site.Name;
...
}
值得一提的是列出的一些问题:
It's worth pointing out some of the issues listed:
注意:TargetSite属性可能不是
如果异常处理程序
处理跨
应用程序域边界的异常,则准确地报告
方法的名称,其中异常为
抛出。
Note: The TargetSite property may not accurately report the name of the method in which an exception was thrown if the exception handler handles an exception across application domain boundaries.
您可以使用@leppie建议的 StackTrace
属性,但请注意,这是一个字符串表示形式堆栈上的帧;所以如果你只想要使用该方法的名称,那么你必须操纵。
You could use the StackTrace
property as @leppie suggests too, but do note that this is a string representation of the frames on the stack; so you'll have to manipulate if you only want the name of the method that threw the execption.
这篇关于如何获取导致异常的方法的名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!