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.