如何获取导致异常的方法的名称 [英] How to get the name of the method that caused the exception

查看:151
本文介绍了如何获取导致异常的方法的名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码如下所示。

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.


获取抛出
当前异常的方法。

Gets the method that throws the current exception.

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

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:


如果抛出此
异常的方法不可用,并且
堆栈跟踪不是空引用
(Visual Basic中没有),TargetSite
从栈
中获取方法。如果堆栈跟踪是一个空的
引用,TargetSite也会返回一个
null引用。

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.

注意: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.

这篇关于如何获取导致异常的方法的名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆