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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With