How can I get the "Original Error" from the stack trace, how does Asp.Net do it?

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

I noticed that the yellow ASP.Net death screen shows several lines of code around the violation line, as well as the stack trace.

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

I want to write this "Original error:" too. Where and how does ASP.net get the "Source Error:" source code from?

+4
source share
1 answer

: , :

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

: ASP.NET


, .NET, , 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 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;
}
...

, , lineNumber , .

+4

Source: https://habr.com/ru/post/1533421/


All Articles