Browse DevX
Sign up for e-mail newsletters from DevX


Errors In Your ASP.NET Code? Don't Throw a Fit, Throw an Exception! : Page 4

Even the best designed applications need to properly manage errors—both the errors you can plan for and those you cannot. In this article, you'll learn error handling techniques in ASP.NET. Topics will range from handling common errors with the Try...Catch syntax to logging unhandled errors into the Windows Event Log.




Building the Right Environment to Support AI, Machine Learning and Deep Learning

Page-level Exception Handling
Your first option for dealing with an unhandled error happens at the page level. There are two functions you can use to manage the error:

Private Sub Page_Error(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Error End Sub


Protected Overrides Sub OnError(ByVal e As System.EventArgs) End Sub

Handling errors in these procedures is simple. A call to Server.GetLastError will return the most recent error. You could also redirect the user to a specific page with Response.Redirect ("MyErrorPage.aspx") or whatever your default error page may be. While it will not be the most common way you will handle errors, the page-level technique for handling errors has its merits.

  • You may need to override the Application_Error or the customErrors setup in the web.config file (more on this later).
  • You can process the error here and if you want to cancel the error processing, so it doesn't go to the Application_Error or customErrors levels, a call to Server.ClearError will do the trick.
Application-Level Exception Handling
Along with page level error handlers, ASP.NET gives developers the ability to provide application-level error handling. This next section will explain how to add application-level exception handling to your ASP.NET applications.

The global.asax File
After the page level error handling, the global.asax file provides the next opportunity to defend against errors.

The global.asax file, also known as the ASP.NET application file, resides in the root directory of an ASP.NET application and is an optional file that contains code for responding to application-level events.

Since the global.asax file is optional, if you do not use one, ASP.NET assumes that you have not defined any application or session event handlers. Visual Studio .NET automatically creates a global.asax when you create a new ASP.NET project.

When an error occurs in your application, ASP.NET executes the Application_Error procedure. This is a great place to track and log errors because it is the most functional place to do so. Odds are that during your ASP.NET development you will find that you will not handle too many errors at the page level. Instead you will opt to handle them at the application level.

As stated before, since the page-level error handling comes first, after ASP.NET calls the Page_Error procedure, then ASP.NET calls the Application_Error procedure. There are a number of things you can do here including e-mailing the system administrator, logging the error to the Windows Event Log, and/or redirect the user to another page with Response.Redirect().

E-mailing the System Administrator

The code in Listing 3 is from the global.asax file. I've removed a number of methods for the sake of space and clarity. I've coded the Application_Error method to send an e-mail containing information about the most recent error.

One thing to note about the code above is that I've added System.Web.Mail to provide SMTP e-mail capability to the Application_Error method.

Logging Errors to the Windows Event Log
The code in Listing 4 is also from the global.asax file. I've added the ability to write information about the current error to the Windows Event Log to the Application_Error method.

Listing 4 expands on the Listing 3 version of the Application_Error method to include writing a record to the event log. If an event log entry does not exist for the entry, one is created before the new entry is added.

The web.config File
ASP.NET provides support for an application configuration file called web.config. ASP.NET lets you use the <customErrors> element of the web.config file as your last chance to gracefully manage an unhandled error since the other two error handlers mentioned so far, Application_Error and Page_Error (or OnError), will get called before customErrors is utilized.

Open up the web.config file for your project and scan down until you find the <customErrors> section. It looks like this:

<customErrors mode="On|Off|RemoteOnly" defaultRedirect="url" <error statusCode="statuscode" redirect="url"/> </customErrors>

The mode attribute plays a key role in how ASP.NET handles custom errors. Table 3 lists the possible settings and their effect.

Table 3: The customErrors mode settings




Specifies that custom errors are enabled. If there is no defaultRedirect specified the user sees a generic error.


Specifies that custom errors are disabled.


Specifies that custom errors are shown only to remote users. ASP.NET errors will display in the user is located on the local host. RemoteOnly is the default setting.

The following will display a generic error page to the user.

<customErrors mode="On" />

In the event an unhandled error such as a Response.Redirect("FakePage.aspx") occurs, the user would see a page similar to Figure 1.

Figure 1: The results of an unhandled error with mode = On without a redirected page to display
Figure 2: The results of an unhandled error with mode = On with a redirected page to display.
To redirect the user to another page you would change it to this:

<customErrors mode="On" defaultRedirect="ErrorPage.htm" />

The same Response.Redirect("FakePage.aspx") line would now result in the user seeing an error page (see Figure 2).

Using the error clause you can also handle specific errors and redirect the user to the error page for each error.

<customErrors mode="On" defaultRedirect="myerror.htm"> <error statusCode="403" redirect="authfailed.aspx"/> <error statusCode="404" redirect="filenotfound.aspx"/> </customErrors>

See, that wasn't all that tough, was it? By using a combination of language features like Try...Catch...Finally and exception objects, as well as understanding the built in error handling mechanisms in ASP.NET, there is no reason why your next ASP.NET application shouldn't be ready to take on the obstacles and errors thrown at it on a daily basis.

Jim Duffy is founder and president of TakeNote Technologies, an award winning training and software development company. He has a BS degree in Computer and Information Systems and over 18 years of programming and training experience. He is an energetic trainer, skilled developer, and has been published in leading developer oriented publications. Jim, a recent Microsoft MVP award recipient, is a popular speaker at regional user groups and developer conferences. He is also the co-host of Computers 2K3, a call-in radio show on WRBZ, 850 The Buzz, in Raleigh, NC. Additional information about Jim and TakeNote Technologies can be found at www.takenote.com. You can reach Jim at jduffy@takenote.com.
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date