get line number in error handling code

G

Guest

I want to get the file name, line number etc. in error handling code in an
asp.net application. I know how to trap errors in the Global.asax and I read
that you can use the stack frame from the System.Diagnostics namespace to get
line numbers provided you release in debug mode but when I use the code below
I merely get the line number, file name etc. of the Global.asax page, not the
page that produced the error. Any way to do this?

protected void Application_Error(Object sender, EventArgs e)

{

string errorLine;

string fileName;

string functionName;

StackTrace st=new StackTrace (0,true);

StackFrame sf=new StackFrame ();


sf=st.GetFrame (0);

fileName = sf.GetFileName ();

errorLine = sf.GetFileLineNumber().ToString();

functionName = sf.GetMethod().ToString();



}
 
S

Steven Cheng[MSFT]

Hi Scott,

Welcome to the ASP.NET newsgroup.

For the component classes in the System.Diagnostics namespace, they provide
the function to inspect the current executing thread's code path and
structure. However, for your scenario, the when you use the
System.Diagnostics components in Application_Error event, it can only
display execution info of the current executiion funciton( the
Application_Error event handler) rather than the unhandled exception
because the exception has occuried before the application_Error event be
fired.

To get the information for the unhandled exception, I think you should use
the Server.GetLastError() method to get the exception object reference and
them get the detailed information of the exception through the Exception
object's properties. For example:

void Application_Error(object sender, EventArgs e)
{
Exception ex = Server.GetLastError();

Context.Items.Add("current_exception", Server.GetLastError());

Server.Transfer("~/MyCustomErrorPage.aspx");

}



then, in my custom error page, we can printout the unhandled exception info:

protected void Page_Load(object sender, EventArgs e)
{
Exception ex = Context.Items["current_exception"] as Exception;

if (ex != null)
{
Response.Write("<br/>-----------------------------");
Response.Write("<br/>Source: " + ex.Source);
Response.Write("<br/>-----------------------------");
Response.Write("<br/>StackTrace: " + ex.StackTrace);
Response.Write("<br/>-----------------------------");

}
}

Hope this helps.

Regards,

Steven Cheng
Microsoft Online Support

Get Secure! www.microsoft.com/security
(This posting is provided "AS IS", with no warranties, and confers no
rights.)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,743
Messages
2,569,478
Members
44,899
Latest member
RodneyMcAu

Latest Threads

Top