Trapping Errors in ASP.NET

Trapping Errors On Page Level

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 =
     "
Offending URL: " + ctx.Request.Url.ToString () +
     "
Source: " + exception.Source +
     "
Message: " + exception.Message +
     "
Stack trace: " + exception.StackTrace;

  ctx.Response.Write (errorInfo);

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

This works for one page only, you may say. To have every page benefit from this kind of error handing we need to take advantage of the Page Controller pattern. You define a base class and have every page inherit from it.

Trapping Errors On Application Level

The idea of capturing errors on the application level is somewhat similar. At this point we need to rehash our understanding of the Global.asax file.

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. The following implementation of this handler is similar to the one above:

protected 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 +
     "
Stack trace: " + exception.StackTrace;

  ctx.Response.Write (errorInfo);

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

Special Thanks to M.Negovan for providing usefull information.

Happy Programming.

Posted by:

No comments posted.

Name :  

Email :  

Comment Below