Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract class and filename from Exception

Tags:

c#

exception

Is it possible to extract the Class name and the Filename from an exception object?

I am looking to integrate better logging into my application, and I want to include detailed information of where the exception occurred.

In MVC the Stacktrace does not return the filename & class name, and I'm a bit lost as to where to look for these.

Thanks

like image 569
anthonyvscode Avatar asked Mar 24 '11 10:03

anthonyvscode


Video Answer


1 Answers

You can create a StackTrace object from an exception object. It will include the StackFrames that the exception has info on. You could then find the file and method names, positions and whatnot if they are available. Of course this should go without saying but all of this is available only if you compiled your assembly to include debugging symbols (which I assume could be available in MVC).

catch (Exception ex)
{
    var st = new StackTrace(ex, true); // create the stack trace
    var query = st.GetFrames()         // get the frames
                  .Select(frame => new
                   {                   // get the info
                       FileName = frame.GetFileName(),
                       LineNumber = frame.GetFileLineNumber(),
                       ColumnNumber = frame.GetFileColumnNumber(),
                       Method = frame.GetMethod(),
                       Class = frame.GetMethod().DeclaringType,
                   });
    // log the information obtained from the query
}
like image 148
Jeff Mercado Avatar answered Oct 15 '22 20:10

Jeff Mercado