C# 如何获取导致异常的方法的名称
我的代码如下所示C# 如何获取导致异常的方法的名称,c#,exception-handling,try-catch,C#,Exception Handling,Try Catch,我的代码如下所示 try { _productRepo.GetAllProductCategories(); } catch (Exception ex) { //Do Something } 我需要一种显示方法名称的方法,假设在上述情况下,如果GetAllProductCategories()方法中引发任何异常,我需要获取此方法名称,即“GetAllProductCategories()”作为结果。有谁能建议我怎么做吗?看看stacktrace 它是异常上的一个属性。在系统上
try
{
_productRepo.GetAllProductCategories();
}
catch (Exception ex)
{
//Do Something
}
我需要一种显示方法名称的方法,假设在上述情况下,如果GetAllProductCategories()方法中引发任何异常,我需要获取此方法名称,即“GetAllProductCategories()”作为结果。有谁能建议我怎么做吗?看看stacktrace 它是异常上的一个属性。在
系统上有一个属性。异常
应该会派上用场
获取引发
目前的例外情况
在您的情况下,您可能需要以下内容:
catch (Exception ex)
{
MethodBase site = ex.TargetSite;
string methodName = site == null ? null : site.Name;
...
}
值得指出的是列出的一些问题:
如果抛出此
异常不可用,并且
堆栈跟踪不是空引用
(Visual Basic中无任何内容),TargetSite
从堆栈中获取方法
跟踪。如果堆栈跟踪为空
引用时,TargetSite也会返回
空引用
注:TargetSite属性可能不适用
准确报告客户的名称
方法,在该方法中创建了异常
如果异常处理程序
处理整个系统中的异常
应用程序域边界
您也可以使用@leppie建议的
StackTrace
属性,但请注意,这是堆栈上帧的字符串表示形式;因此,如果您只需要抛出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;
}
基本上,如果TargetSite()做了您想做的事情,那么就不要再继续了。但是,通常在日志处理程序中,异常对象不可用(即跟踪和审核),因此需要一个新的StackTrace()对象来检索最后执行的方法,即日志方法之前的方法。简单答案是什么?它是位于调用堆栈顶部的方法。这是在异常发生之前最近调用的方法。:)我通过检查这个答案解决了GetType所指的是什么?这是您创建的另一种方法吗?内置的GetType需要引用一个对象。@KingOfHypocrites-GetType()正在从当前类调用。我看不出这如何适用于所问的问题。此代码生成一个全新的
StackTrace
对象,与异常的堆栈跟踪无关。另外,.NET已经有了一种非常好(而且更可靠)的方法来获取当前正在执行的方法的MethodInfo
对象:@PeterDuniho-它表明当前正在执行的方法名称可以从StackFrame获得。因此,在错误情况下,Exception对象可用于创建StackTrace对象,该对象可用于获取StackFrames。该方法可以很容易地修改为接受异常对象,但代码更多的是演示如何使用StackFrame。还请注意,MethodBase.GetCurrentMethod()只提供正在执行的当前方法的名称,而不提供引发异常的方法。@ChrisGessler如何在异步方法中获取mathod?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);
}
}