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

问题描述

我知道了。类似的问题已经问。

I know. A similar question has already asked.



  • How to get the name of the method that caused the exception

但我还没有得到来自精确的解决方案。

but I haven't got the exact solution from that.

我有,我有一个方法,一个按钮单击事件 FillCombo()

I have a button click event in which I have a method FillCombo().

按钮的Click事件

private void button1_Click(object sender, EventArgs e)
{
      try
      {
          cmbTemplates.Items.Clear();
          lstFiles.Clear();
          FillCombo();
      }
      catch (Exception ex)
      {
           MethodBase site = ex.TargetSite;
           Log(ex.ToString(), site == null ? null : site.Name);
      }
}

当我调试,我发现,从发生异常 FillCombo()方法。从那以后,我得到 site.Name 的值 WinIOError 而不是 FillCombo

When I debugged, I found that the exception occurs from FillCombo() method. After that I get the value of site.Name as WinIOError instead of FillCombo.

我试过另一种方法 GetExecutingMethodName()这是由回答的克里斯·格斯勒 获得命名导致异常问题的方法。所以我尝试发送,使用引起异常的方法的名称 GetExecutingMethodName()

I tried another method GetExecutingMethodName() which was answered by Chris Gessler in How to get the name of the method that caused the exception question. So I tried sending the name of method that caused exception using GetExecutingMethodName() method

Log(ex.ToString(), GetExecutingMethodName());



但我得到的结果为 System.Windows.Forms.Control.OnClick 而不是 FillCombo

如何获得的实际名称导致异常的方法?

推荐答案

.NET支持获得从异常堆栈跟踪信息。可以筛选出通过检查第一个帧(原点)的方法(和它的名字)。

.net supports getting the stack trace information from an exception. You could filter out the method (and its name) by examining the first frame (origin).

new StackTrace(ex).GetFrame(0).GetMethod().Name

这将可能给你完全一样的targetsite(胜利IO),但你可以检查的第一个用户代码的堆栈跟踪,或。在你的类型,或任何你需要的第一帧

This would probably give you exactly the same as the targetsite (the win io), but you can examine the stacktrace for the first user code, or the first frame in your type, or whichever your needs.

例如,在当前的组装得到的罪魁祸首运动员的名称:

For example, getting the name of the culprit thrower in your current assembly:

var s = new StackTrace(ex);
var thisasm = Assembly.GetExecutingAssembly();
var methodname = s.GetFrames().Select(f => f.GetMethod()).First(m => m.Module.Assembly == thisasm).Name;

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

09-03 14:41