Search

Redirecting errors to Errors.aspx page

Although everyone wants to code bugfree, but exception are generated with the change of environment. Here is a sample as how to setup an error.aspx to

// This is the error page looking for message & stack over the http context
public partial class Errors : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!HttpContext.Current.Items.Contains("Title") && !HttpContext.Current.Items.Contains("Message"))
{
Response.Redirect("/");
}
else
{
//these can me a string literal or asp.net label
msgtitle.Text = "<br/><span class='mtitle'>" + (String)HttpContext.Current.Items["Title"] + "</span><br/>";
msgcontent.Text = "<span class='mcontent'>" + (String)HttpContext.Current.Items["Message"] + "<span/>";
msgStack.Text = "<b>Stack:</b><br/>" + (String) HttpContext.Current.Items["Stack"];
}
}
}



according to MSDN.. Server.Transfer acts as an efficient replacement for the Response.Redirect method. Response.Redirect specifies to the browser to request a different page. Because a redirect forces a new page request, the browser makes two requests to the Web server, so the Web server handles an extra request. IIS 5.0 introduced a new function, Server.Transfer, which transfers execution to a different ASP page on the server. This avoids the extra request, resulting in better overall system performance, as well as a better user experience.

so we aregoing to use it to throw the error, you can make use of this action delegate in every page to throw the exception


// setup for error message for other page -pass the title/message to the error page
Action RedirectError = (title, message,stack) =>
{
//adds the title,message & stack from the passed parameter to the HttpContext
HttpContext.Current.Items.Add("Title", title);
HttpContext.Current.Items.Add("Message",message);
// adds the stacktrace to httpcontext if it's not null
if(stack != null)
HttpContext.Current.Items.Add("Stack", stack);

//transfers the execution to a different aspx page
Server.Transfer("Errors.aspx");
};