Get Method name that threw exception

前端 未结 3 2044
無奈伤痛
無奈伤痛 2020-12-09 16:57

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

3条回答
  •  半阙折子戏
    2020-12-09 17:24

    .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
    

    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;
    

提交回复
热议问题