1

I was wondering if I can get the caller of the method that caused an exception in .Net Core

For example:

There is a method called CallerMethod() in the Main Window Window_Loaded event which calls another method in which I'm catching the exception.

I need to get CallerMethod name without all the Environment.StackTrace information. Furthermore, exception.StackTrace only shows the method that throws the exception and not the call stack

I hope that I've properly explained the issue.

janw
  • 8,758
  • 11
  • 40
  • 62
user11286025
  • 102
  • 9
  • https://stackoverflow.com/questions/43609326/stackframe-does-not-get-all-of-frames – Daniel A. White Jul 01 '20 at 14:57
  • Note that the stack trace is affected by compiler optimizations in release build, so it may not always be what you think it is. – Alejandro Jul 01 '20 at 14:58
  • @DanielA.White Thank you for the link – user11286025 Jul 01 '20 at 15:01
  • @Alejandro your note is very useful. The thing is that I can read CallerMethod name in the stack trace, but is there a way to only get its information for logging purposes and not the entire StackTrace? – user11286025 Jul 01 '20 at 15:03
  • 1
    Without a stacktrace: [CallerMemberNameAttribute](https://learn.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.callermembernameattribute) – Hans Kesting Jul 01 '20 at 15:24
  • @HansKesting thank you this is helpful. I was able to get the the DoProcessing name using the attribute. But, my question is can I get the method's path/name in which I used the DoProcessing metthod? – user11286025 Jul 01 '20 at 15:30
  • You can only go one level up, but if you are interested in callers of DoProcessing, why not add the attribute there? – Hans Kesting Jul 01 '20 at 15:33
  • @HansKesting I wasn't fully aware of this, thanks. So, a solution would be to add the attribute to all the methods resembling DoProcessing in my application. – user11286025 Jul 01 '20 at 15:38

0 Answers0