gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 02:59:33 24 4
gpt4 key购买 nike

我的代码如下所示。

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

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

最佳答案

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

Gets the method that throws the current exception.

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

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

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

If the method that throws this exception is not available and the stack trace is not a null reference (Nothing in Visual Basic), TargetSite obtains the method from the stack trace. If the stack trace is a null reference, TargetSite also returns a null reference.

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 属性,但请注意这是堆栈上帧的字符串表示;因此,如果您只想要引发执行的方法的名称,则必须进行操作。

关于c# - 如何获取导致异常的方法的名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4598255/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com