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

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

问题描述

我的code外观如下图所示。

My code looks as below.

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?

推荐答案

有一个<一个href=\"http://msdn.microsoft.com/en-us/library/system.exception.targetsite%28VS.90%29.aspx\"><$c$c>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中为Nothing),TargetSite
  从堆栈获得方法
  跟踪。如果堆栈跟踪是一个空
  参考TargetSite也返回
  空引用。

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暗示过,但千万注意,这是一个字符串,再叠上的框架presentation;所以你必须操纵,如果你只想要的名称的那个扔execption方法。

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天全站免登陆