Showing posts with label Exception Handling. Show all posts
Showing posts with label Exception Handling. Show all posts

Thursday, February 14, 2008

Asp.Net Custom Error Pages based on Error Code

From the moment you request a page in your browser to the moment you see a response on your screen a complex process takes place on the server. Your request travels through the ASP.NET pipeline.

When any exception is thrown now—be it a general exception or a 404—it will end up in Application_Error. We can trap errors and display friendly meaningful messages to users by following method..

void Application_Error(object sender, EventArgs e)
{
// At this point we have information about the error
HttpContext ctx = HttpContext.Current;

Exception exception = ctx.Server.GetLastError();

string errorInfo = "Offending URL: " + ctx.Request.Url.ToString() +" Source: " + exception.Source +
" Message: " + exception.Message +" TARGETSITE: " + exception.TargetSite +" Stack trace: " + exception.StackTrace;

ctx.Response.Write(errorInfo);

if (exception is HttpException && ((HttpException)exception).GetHttpCode() == 404)
{
string strurl = ctx.Request.Url.ToString();
strurl = strurl.Substring(strurl.ToLower().IndexOf("account"));
strurl = strurl.Substring(0, strurl.IndexOf("/"));
if (strurl.ToLower() == "account")
{
// To let the page finish running we clear the error
ctx.Server.ClearError();

ctx.Response.Redirect("a.html");
}
else
{
// To let the page finish running we clear the error
ctx.Server.ClearError();

ctx.Response.Redirect("b.html");
}
}
else
{
// To let the page finish running we clear the error
ctx.Server.ClearError();

ctx.Response.Redirect("c.html");
}
}