How to register an exception with a full call stack?

I want to use ELMAH to register an exception (without metadata to the call stack), and it logs the entire call stack.

Code example:

protected void Page_Load(object sender, EventArgs e) { DoSomething(); } private void DoSomething() { try { TrySomething(); } catch (Exception ex) { LogException(ex); } } private void TrySomething() { throw new NotImplementedException(); } public static void LogException(Exception ex) { var currentStack = new System.Diagnostics.StackTrace(true); Elmah.ErrorSignal.FromCurrentContext().Raise(ex); } 

Now, in the LogException method, I see a call stack telling DoSomething () called TrySomething (), and this throws an exception, but I don’t see how the call stack shows me Page_Load () called DoSomething (). I want to see the full call stack.

An example of what ex.StackTrace looks inside the LogException method:

 at WebApplication1._Default.TrySomething() in C:\Projects\test\GeneralTests\WebApplication1\Default.aspx.cs:line 26 at WebApplication1._Default.DoSomething() in C:\Projects\test\GeneralTests\WebApplication1\Default.aspx.cs:line 20 

I can get the full call stack from System.Diagnostics.StackTrace (), for example:

 at WebApplication1._Default.LogException(Exception ex) at WebApplication1._Default.DoSomething() at WebApplication1._Default.Page_Load(Object sender, EventArgs e) [snip] 

(and I can get line numbers and source file data by skipping every StackTrace frame)

But how do I insert this into an Exception or create a new exception with this call stack detail? Is there an elegant way to do this? Am I missing something really obvious ?!

+4
source share
3 answers

You can do something like this to get the full stack on error:

 var currentStack = new System.Diagnostics.StackTrace(true); return currentStack.ToString(); 
+4
source

When an application is compiled without debug flags, the stack is not necessarily saved at runtime. You can guarantee only every recordable item by adding try / catch to each method.

+1
source

Have you looked at the results of Exception.ToString ()? It includes a stack trace. Does it include the view you are looking for?

+1
source

All Articles