Tuesday, 27 September 2011

Asp.net custom error page

ASP.NET provides a simple yet powerful way to deal with errors that occur in your web applications. We will look at several ways to trap errors and display friendly meaningful messages to users. We will then take the discussion a step further and learn how to be instantly notified about problems so you can cope with them right away. As a geek touch we will also track the path 404's travel.
In the days of "classic" ASP you used to get cryptic—an often times downright misleading—error messages. "White pages" leave your visitors in the dark who don't know what happened and what to do next besides closing the browser or navigating away.
It's obvious that "white pages" are ugly but there's another angle to this—ASP.NET displays an exception stack trace which may reveal what your code does and how it works. These days, when the word "security" is in vogue, this could be a dangerous side effect.
Custom error pages are not luxury any more, they are a must-have. You have several ways to implement them.

Every time you create a web form in Visual Studio .NET you see that your page class derives from System.Web.UI.Page. The Page object helps you trap page-level errors. For this to happen you need to override its OnError method as follows:

protected override void OnError(EventArgs e)
{
  // At this point we have information about the error
  HttpContext ctx = HttpContext.Current;

  Exception exception = ctx.Server.GetLastError ();

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

  ctx.Response.Write (errorInfo);

  // --------------------------------------------------
  // To let the page finish running we clear the error
  // --------------------------------------------------
  ctx.Server.ClearError ();
 
  base.OnError (e);
}

No comments:

Post a Comment