Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - How to get Class Name and Line Number when an Exception is called

Tags:

c#

asp.net

I need two methods, one for getting the Class from where the exception was called, and another one which gets the line number where an exception was called.

So far I have this code, which gets me the Class Name and Line Number together (example: DatabaseHandler.cs:line 70):

    private string GetClassAndLine()
    {
        string tempName = e.GetBaseException().ToString();
        int tempPosition = 0;
        int length = tempName.Length;
        for (int i = 0; i < length; i++)
        {
            if (tempName.ElementAt(i).Equals('\\'))
            {
                tempPosition = i + 1;
            }
        }
        return tempName.Substring(tempPosition, length - tempPosition);
    }

So if you have any ideas how I could get them individually, it would be of great help. These are then passed into Oracle to store any exceptions which occur.

Update 2:

I am currently testing this code, as some suggested:

        private string GetClassName()
    {
        System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(e, true); 
        return trace.GetFrame(0).GetMethod().ReflectedType.FullName;
    }

    private int GetLineNumber()
    {
        System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(e, true); 
        return trace.GetFrame(0).GetFileLineNumber();
    }

This is what was returned at a particular Database Exception. No Line Number or Class Name where it was triggered. How can I get that?

    Error was found at Class: Oracle.DataAccess.Client.OracleException.     
    Line Number: 0

What I want is for Example: "Class: Logging.cs, Line: 57"

Thanks, Ryan

like image 915
Ryan S Avatar asked Aug 09 '11 10:08

Ryan S


1 Answers

You can do like this

try
{
    // Some code that can cause an exception.

    throw new Exception("An error has happened");
}
catch (Exception ex)
{
    System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);

    Console.WriteLine(trace.GetFrame(0).GetMethod().ReflectedType.FullName);
    Console.WriteLine("Line: " + trace.GetFrame(0).GetFileLineNumber());
    Console.WriteLine("Column: " + trace.GetFrame(0).GetFileColumnNumber());
}
like image 66
Peter PAD Avatar answered Sep 20 '22 00:09

Peter PAD