5

I am running .NET 3.5 and IIS7.

I was trying to use customErrors to redirect to a custom error page that could still display the exception details, stack trace, etc. I had a hard time getting it to work, trying about 20 different approaches I found online (mostly on stackoverflow), some of which were slight variations of others. I preferred to have the redirect to happen in Web.config because I wanted the custom error page to be easily found/edited outside the code.

Here's what I finally got to work. I'm posting because I tried so many of the more complex approaches I found here and they didn't work for me, and just wanted to post the simple one that ultimately did.

Web.config:

<customErrors mode="RemoteOnly" defaultRedirect="~/Error.aspx" redirectMode="ResponseRewrite" />

Without the redirectMode="ResponseRewrite", I could not access the exception details from my custom error page.

Error.aspx

protected void Page_Load(object sender, EventArgs e)
{
    Exception ex = Server.GetLastError();
    if (ex != null)
    {
        if (ex.GetBaseException() != null) ex = ex.GetBaseException();
        litErrorMessage.Text = String.Format("<div class=\"error\">{0}</div>", ex.Message);
        litErrorStackTrace.Text = String.Format("<b>Source:</b>\n{0}\n<b>Stack Trace:</b>\n{1}\n", ex.Source, ex.StackTrace);
    }
    else
    {
        litErrorStackTrace.Text = "No Exception information available.";
    }
}

I also tried using HttpException ex = (HttpException)HttpContext.Current.Server.GetLastError();, as seen in some examples, but that did not work.

I also tried all kinds of code in Global.asax -> Application_Error, but it turns out it was not necessary. After trying all kinds of code there, including storing session variables, Application_Error is now empty.

Lys777
  • 386
  • 1
  • 2
  • 11
  • Post the question and answer separately. You can answer your own question. – Ehsan Jun 12 '14 at 02:15
  • Didn't have enough rep to do that until 8 hrs later, and I didn't want people to waste time on my already answered question. Thanks though for the tip. – Lys777 Jun 13 '14 at 18:35
  • it is perfectly alright to answer your own question. As it may help someone else one day. – Ehsan Jun 14 '14 at 08:30

0 Answers0