Search code examples
asp.neterror-handlingglobal-asax

Return the Method Name and Line Number upon Error in page in global.asax file


My code is as below , would like to get Page Name , Method Name and Page Line Number where error occured.

void Application_Error(object sender, EventArgs e) 
    { 
        // Code that runs when an unhandled error occurs

        if (HttpContext.Current.Server.GetLastError() != null)
        {

            Exception ex = HttpContext.Current.Server.GetLastError().GetBaseException();

            string urlPath = Request.Url.ToString();
            string errorMsg = ex.Message; 

            // Need help on below .....
            string pageName =  ??????
            string pageMethodName =  ??????
            string pageLineNumber =  ??????

        }
    }

The ex.StackTrace Property works when I user it with try/catch in the page.

   private void sampletTest()
   {
    try
    {
        //throwing Exception
        using (SqlConnection connection = new SqlConnection(""))
        {
            connection.Open();
        }
    }
    catch (Exception exception)
    {
        //Get a StackTrace object for the exception
        StackTrace st = new StackTrace(exception, true);

        //Get the first stack frame
        StackFrame frame = st.GetFrame(st.FrameCount - 1);

        //Get the file name
        string fileName = frame.GetFileName(); //returns filename

        //Get the method name
        string methodName = frame.GetMethod().Name; // returns methodname

        //Get the line number from the stack frame
        int line = frame.GetFileLineNumber(); //returns line number

 }

}

The above code return the line number , method name and page name as expected.

The below code when used in global.asax , doesn't return line number , methodname

 if (HttpContext.Current.Server.GetLastError() != null)
    {
        Exception myException =
        HttpContext.Current.Server.GetLastError().GetBaseException();

        StackTrace st = new StackTrace(myException, true);

        //Get the first stack frame
        StackFrame frame = st.GetFrame(st.FrameCount - 1); 

        //Get the file name
        string fileName = frame.GetFileName(); //returns null

        //Get the method name
        string methodName = frame.GetMethod().Name; //returns *"ProcessRequestMain"*

        //Get the line number from the stack frame
        int line = frame.GetFileLineNumber(); //returns 0
   }

Solution

  • It worked for me this way (GetMethod and GetFileNumber methods were not working):

    Dim ex As Exception = Server.GetLastError.GetBaseException
    
    Dim trace As New Diagnostics.StackTrace(ex, True)
    
    In trace you have the method and the line, so you can easily print
    
    trace.toString()