lax
lax

Reputation: 518

custom error page in asp.net

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>

Upvotes: 1

Views: 7856

Answers (5)

Azhar Mansuri
Azhar Mansuri

Reputation: 705

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

Upvotes: 1

laszlokiss88
laszlokiss88

Reputation: 4071

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
}

Upvotes: 1

Dai
Dai

Reputation: 154995

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.

Upvotes: 2

Pierre-Marie Le Brun
Pierre-Marie Le Brun

Reputation: 143

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;
}

Upvotes: 4

Kinexus
Kinexus

Reputation: 12904

You can access the error using Server.GetLastError;

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

For more information : HttpServerUtility.GetLastError Method

Upvotes: 0

Related Questions