简体   繁体   中英

How do you access the Source Error, Source File and Line Number of an exception to use in a custom error page?

Basically I want to take the following: 替代文字

And make it match the styling of the rest of the application.

I am creating a custom error page in my C# based project and I want it to be able to show the same information that is displayed in the ASP.NET default error page. From fiddling with reflector I can see that this is generated through HttpException.GetHtmlErrorMessage() but when I try to use this in my exception it returns null .

Iain,

I used this code in order to do something similar on a custom error page. I'm not sure if showing the exact source code region that caused the error is possible using the Exception object, but I was able to use the stack trace, which includes line numbers and method names:

If Not IsPostBack Then
    Dim ex As Exception = Server.GetLastError().GetBaseException()
    lblExceptionMessage.Text = ex.Message.ToString()
    lblStackTrace.Text = ex.StackTrace().Replace(System.Environment.NewLine, "<br />")
End If

You can also use ex.TargetSite to get just the method name that threw the exception.

HTH,

Mike

This answer is a little old, but none of the existing answers really deal with the original question. I was looking for something similar, and could not find anything, so here is my quick and dirty solution.

First, need to actually break down the stack trace and get the top level frame.

var st = new System.Diagnostics.StackTrace(this.Exception, true);
var frame = st.GetFrame(0);

Then, need to read the file that the frame refers to (note, this will only work, I believe, if the PDB files are available) and figure out which lines you want to display. Here's a method if passed an exception will send back a dictionary with the potential lines. You can then prettify it however you want.

public Dictionary<int, string> GetFileInfo(Exception ex, int linesBefore, int linesAfter)
    {
        Dictionary<int, string> sb = new Dictionary<int, string>();
        var st = new System.Diagnostics.StackTrace(ex, true);
        var frame = st.GetFrame(0);

        using (System.IO.StreamReader file = new System.IO.StreamReader(frame.GetFileName()))
        {
            if (file == null)
                return sb;

            int counter = 0;
            int line = frame.GetFileLineNumber();
            int lastline =  line + linesAfter;
            int firstline = line - linesBefore;

            while (!file.EndOfStream && counter < lastline)
            {
                string str = file.ReadLine();
                if (counter > firstline && !string.IsNullOrWhiteSpace(str))
                    sb.Add(counter, str);
                counter++;
            }
        }

        return sb;

    }

You don't need to add a filter to do event grabbing, just handle Application_Error in global.asax.cs. Server.GetLastError( ) will have the exception information

Yeah, erm... No. The error shown in the original question shows a parsing/compilation error - these errors happen in the HttpHandler pipeline for ASP.NET (ISAPI Filter in older IIS versions) ie before your application is event started, so before any of the events in Global.asax.

Although you can specify a custom error page (in web.config, machine.config, or IIS metabase), these can only be HTML files.

1) if you're only interested in exceptions which arise in your code (ie your code compiles, but then an exception is thrown) then you can use Dan's suggestion from above and handle the Application_Error event in Glocal.asax.

If you want to handle ASP.NET exceptions (eg Parsing/Compilation errors, config files errors, etc) then you'll need to hook in (or replace) the ASP.NET HttpHandler.

You could wrap the existing handler by writing your own, and catching any exceptions, then redirecting to another error page.

You'd specify your handler in your web.config file (or machine.config if it's a global handler).

There are some good tutorials on the web on how to do this. Try starting here: http://msdn.microsoft.com/en-us/library/f3ff8w4a(VS.71).aspx

(main problem is: to catch parsing/compilation errors you need to write a handler/filter which is a level above the ASP.NET handler/filter (I believe)).

Hope this helps, Dourn.

I've never tried doing this but all IIS errors are recorded to the event log. You could try to read the last error from the event log and display that if it is already written.

You'd also want to add a filter to your event grabbing to ensure you're showing events from your application and that there aren't other error events within a significant amount of time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM