0

I have some apps that have standardized error handling, doing a MessageBox.show and writing to a log each time there's an exception. Right now, they use quoted literals to identify the method or function that caused the error. As a result of developers copying and pasting code, these literals are often incorrect, plus it's extra work to change them each time.

I'd like to create generic handling code that will use either reflection or diagnostics to get the correct method name and display and log it. By correct method, I mean the method in the source code, not some .net framework method or mscorlib call. I'd also like it to be insensitive to inlining, and give me the true source method name whether it's been inlined or not. And of course, I'd prefer not to take the double performance hit from using reflection and disabling inlining at the project/solution level. Oh, and I'd like an egg in my beer.

I think TargetSite is what I want, but I can't find any documentation anywhere that specifies how it reacts to inlining. If it won't work, and searching stacktrace using linq won't work either, then I'm open to suggestions.

Here's my attempt at searching the stacktrace:

public static string CurrentMethodInClass(string className, Exception ex)
{
    var stackTrace = new StackTrace(ex);
    var lastFrame = stackTrace.GetFrames().FirstOrDefault(frame => frame.GetMethod().DeclaringType.FullName == className);
    string methodName = string.Empty;
    if (lastFrame != null)
        methodName = lastFrame.GetMethod().Name;
    return methodName;
}
Nisarg Shah
  • 14,151
  • 6
  • 34
  • 55
  • Visual Studio code snippet and usage of `nameof`? So devs don't c&p but can add the lines with a shortcut and if they refactor the method name, it will also be changed when using nameof. – Fildor Mar 19 '18 at 15:20
  • I'm almost sure the only possibility to stop inlining is to use NoInline https://stackoverflow.com/questions/5169219/preventing-jit-inlining-on-a-method – Evgeny Gorbovoy Mar 19 '18 at 15:24
  • If your handling method is expected to be called locally, meaning you have a catch in every method, you could just use *CallerMemberName* – user6144226 Mar 19 '18 at 15:45
  • Well, the devs aren't doing c&p in order to get the error handling code, they're doing c&p to get the logic, the error code is incidental. If they c&p between classes, this would generate a compile error, good because it would force them to fix it, but within a class, they could leave it wrong and the log would point to 2 places. But thanks. – Aging Hippie Mar 19 '18 at 15:50
  • If they c&p _to get the logic_ **they are doing software development wrong** ! – Fildor Mar 19 '18 at 15:52
  • That sounds like it might be the solution, 6144226, thanks. Do you know if it still works with inlining? – Aging Hippie Mar 19 '18 at 16:07
  • Fildor, you're correct, but I'm not in a position to change the culture. – Aging Hippie Mar 19 '18 at 16:09

0 Answers0