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

◇◆丶佛笑我妖孽 提交于 2019-12-12 03:00:35

问题


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
   }

回答1:


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()


来源:https://stackoverflow.com/questions/24658190/return-the-method-name-and-line-number-upon-error-in-page-in-global-asax-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!