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;
}