0

In my code I have a generic method that logs the errors, something like this

static void LogError(Exception ex, string methodName)
{
    // the actual logging is much more complex
    Console.WriteLine(methodName);
    Console.WriteLine(ex);
}

Now, in every method I have to use try/catch in such a form

static void TestMethod1()
{
    try
    {
        // do the actual operation here
        string s = null;

        s = s.Substring(1);
    }
    catch (Exception exec)
    {
        LogError(exec, System.Reflection.MethodBase.GetCurrentMethod().Name);
    }
}

if an exception happens the information logged will display the exact method name TestMethod1.

While this work I don't like to add try/catch to every method, so I thought to write such a replacement

static void DoWithLog(Action a)
{
    try
    {
        a();
    }
    catch (Exception ex)
    {
        LogError(ex, System.Reflection.MethodBase.GetCurrentMethod().Name);
    }
}

private static void TestMethod2()
{
    DoWithLog(() =>
        {
            string s = null;

            s = s.Substring(1);
        });
}

this way in my method I actually write needed code with try/catch. While this is working as expected I don't get anymore the original method name, I get the lambda name. Is there a way to get from exception stack trace the original method name TestMethod2 ?

P.S. I know is not good to enclose everything in try/catch and a global exception handler must be used, but this how this project was written much before me, and nobody is wiling to change it.

Dmitry
  • 13,797
  • 6
  • 32
  • 48
Eugen
  • 2,934
  • 2
  • 26
  • 47
  • 2
    That is an absolutely horrible way to "handle" exceptions, and in fact _ignores_ all exceptions after logging them. Furthermore, you don't need to explicitly log the method name, as it's in the stack trace. See http://stackoverflow.com/questions/2469822/handling-exceptions-is-this-a-good-way/2469864#2469864 – John Saunders Apr 21 '14 at 19:12
  • possible duplicate of [Retrieving the calling method name from within a method](http://stackoverflow.com/questions/615940/retrieving-the-calling-method-name-from-within-a-method) – Alberto Apr 21 '14 at 20:18

1 Answers1

1

This should work.

StackTrace stackTrace = new StackTrace();
MethodBase methodBase = stackTrace.GetFrame(1).GetMethod();
Console.WriteLine(methodBase.Name);

Taken from similar question:

Retrieving the calling method name from within a method

Community
  • 1
  • 1
milagvoniduak
  • 3,214
  • 1
  • 18
  • 18