出错时返回方法名称和行号在global.asax文件中的页面中

问题描述 投票:0回答:1

我的代码如下,想获取发生错误的页面名称,方法名称和页面行号。

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 =  ??????

        }
    }

ex.StackTrace属性在页面中通过try / catch使用时有效。

   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

 }

}

上面的代码按预期返回行号,方法名和页面名。

下面的代码在global.asax中使用时,不返回行号,方法名

 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
   }
asp.net error-handling global-asax
1个回答
0
投票

它以这种方式为我工作(GetMethod和GetFileNumber方法不起作用):

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()
© www.soinside.com 2019 - 2024. All rights reserved.