1

I have web application in asp.net. I have to implement custom error page. Means if any eror occurs(runtime). I have to display exception and stacktrace on errorpage.aspx shall i handle from master page or on page level and how.

<customErrors mode="On" defaultRedirect="~/Error_Page.aspx"></customErrors>
lax
  • 518
  • 2
  • 11
  • 26
  • 1
    If you set custom errors to Off it'll just show you the error and stacktrace in the asp default exception page. Don't know if that'll do it for you? – middelpat Dec 12 '12 at 09:58
  • i have to write details and stack trace about error on ErrorPage.aspx from users point of view – lax Dec 12 '12 at 10:11

5 Answers5

4

You can handle it in global.asax :

protected void Application_Error(object sender, EventArgs e)
{
   Exception ex = System.Web.HttpContext.Current.Error;
   //Use here
   System.Web.HttpContext.Current.ClearError();
   //Write custom error page in response
   System.Web.HttpContext.Current.Response.Write(customErrorPageContent);
   System.Web.HttpContext.Current.Response.StatusCode = 500;
}
2

Please do not use Redirection as a means of displaying error messages, because it breaks HTTP. In case of an error, it makes sense for the server to return an appropriate 4xx or 5xx response, and not a 301 Redirection to a 200 OK response. I don't know why Microsoft added this option to ASP.NET's Custom Error Page feature, but fortunately you don't need to use it.

I recommend using IIS Manager to generate your web.config file for you. As for handling the error, open your Global.asax.cs file and add a method for Application_Error, then call Server.GetLastError() from within.

Dai
  • 141,631
  • 28
  • 261
  • 374
1

Use Elmah dll for displaying your error with nice UI. You can maintain log using this DLL.

Azhar Mansuri
  • 665
  • 1
  • 7
  • 22
1

In the Global.asax

void Application_Error(object sender, EventArgs e) 
{    
    Session["error"] = Server.GetLastError().InnerException; 
}
void Session_Start(object sender, EventArgs e) 
{      
    Session["error"] = null;
}

In the Error_Page Page_Load event

if (Session["error"] != null)
{
    // You have the error, do what you want
}
laszlokiss88
  • 4,001
  • 3
  • 20
  • 26
  • 1
    This won't work as the Session object is not available when the Application_Error event is triggered. – Arthur Aug 14 '13 at 11:58
0

You can access the error using Server.GetLastError;

var exception = Server.GetLastError();
  if (exception != null)
    {
       //Display Information here
    }

For more information : HttpServerUtility.GetLastError Method

ChrisBint
  • 12,773
  • 6
  • 40
  • 62
  • is this efficient way..means i have to place above on every page..should i handle any errors on master page only.. – lax Dec 12 '12 at 10:06