Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the "Source Error" from a stack trace like Asp.Net does?

Tags:

.net

asp.net

I have an asp.net application, and if there is an exception in the code I catch it log some details (the stack trace, exception details etc) to a database and return a reference code to the client.

I noticed that the ASP.Net yellow screen of death shows a few lines of code around the offending line as well as the stack trace.

Asp.Net Yellow Screen of Death showing "Source Error"

I want to log that "Source Error:" too. Where and how does the ASP.net get the "Source Error:" source code from?

like image 986
Daniel James Bryars Avatar asked Mar 25 '14 21:03

Daniel James Bryars


1 Answers

Edit: If you want the file name and line number of the error, you can get it this way:

var exc = Server.GetLastError();
var frame = new StackTrace(exc, true).GetFrame(0);

var sourceFile = frame.GetFileName();
var lineNumber = frame.GetFileLineNumber();

// sourceFile = c:\path\to\source\file.aspx
// lineNumber = 123

Reference: How does ASP.NET get line numbers in it's generic error handler


It looks like the code in the .NET framework responsible for getting source information is System.Web.FormatterWithFileInfo.GetSourceFileLines().

...
for (int i=1; ; i++) {
    // Get the current line from the source file
    string sourceLine = reader.ReadLine();
    if (sourceLine == null)
        break;

    // If it's the error line, make it red
    if (i == lineNumber)
        sb.Append("<font color=red>");

    // Is it in the range we want to display
    if (i >= lineNumber-errorRange && i <= lineNumber+errorRange) {
        fFoundLine = true;
        String linestr = i.ToString("G", CultureInfo.CurrentCulture);

        sb.Append(SR.GetString(SR.WithFile_Line_Num, linestr));
        if (linestr.Length < 3)
            sb.Append(' ', 3 - linestr.Length);
        sb.Append(HttpUtility.HtmlEncode(sourceLine));

        if (i != lineNumber+errorRange)
            sb.Append("\r\n");
    }

    if (i == lineNumber)
        sb.Append("</font>");

    if (i>lineNumber+errorRange)
        break;
}
...

Basically it does nothing more than open the source file, and find the line referenced by lineNumber in the error, along with 2 lines before and after.

like image 142
mellamokb Avatar answered Oct 11 '22 17:10

mellamokb