Handling Exceptions with ASP.NET | WebReference

Handling Exceptions with ASP.NET

By Ryan Butler


[next]

As developers, we're faced with many obstacles, including learning new technologies against tight deadlines, creating effective and efficient user interfaces which clients and visitors demand, trying to make sense out of complicated business solutions, and helping our visitors work faster and easier, all while trying to deliver our solution(s) on time and on budget. It becomes apparent quickly that we encounter many different obstacles during an application's lifecycle, but one that is sometimes left by the side of the road is handling exceptions.

Exceptions in our solutions essentially make them useless, and more importantly, they frustrate our users because they don't understand them. They just want the solution to work as desired. Exceptions to our solutions can occur from many different avenues. In the following article, we'll learn about a few of these including database connections, use of try/catch blocks, build or run-time errors and incorrectly supplying parameters to a stored procedure. We'll also cover how to handle an exception gracefully from a visitor's perspective, but give a developer the less than pleasant information necessary in order to debug the problem.

Requirements

You will need the following software to complete this article:
  • Microsoft SQL Server 2008
  • Microsoft Visual Studio 2008 or 2010

Create the Database from the Backup File

Open SQL Server: Start→Programs →Microsoft SQL Server 2008, and connect to your database server, whether it's local or remote. After connecting to your database, create a table by following these steps:

  1. Right click on Databases and select New Database.
  2. In the New Database window, type mwd_ExceptionHandling in the database name text field and then click OK.
  3. Right click on your database and select Tasks →Restore→Database.
  4. In the restore database window, select From device as shown below:



    Click here for larger image

    Figure 1. Be Sure to Click From device Caption

  5. Left click the ellipses as shown below:



    Click here for larger image

    Figure 2. Left Click the Ellipses

  6. In specify backup back up, left click the Add button.
  7. Select mwd_ExceptionHandling.bak.
  8. Click OK.
  9. Click OK again.
  10. Left click the check box for the backup you just selected in Step 6.
  11. From the restore database window, left click Options on the left side.
  12. Left click the first check box to overwrite the existing database and click OK.
  13. From the restore database window, left click OK.

Take a few minutes and explore the database table Person. If you open the table, you'll notice the following:

  • One table, with five columns, including a primary key, and a global unique identifier
  • Three stored procedures:
    • spExceptionHandlingListAll
    • spExceptionHandlingUpdate
    • spExceptionHandlingViewParticipant

The first one lists all participants from our database. The second updates a participant while viewing their existing information, and the last allows us to view specific participant information.

A Quick Note About Stored Procedures

In databases, you can think of stored procedures as blocks of SQL code that have been executed against the database, in other words, cached. This is great for multiple reasons including:

  • Because the SQL code is executed against the database, it's already indexed on the database and knows the tables it needs, which means performance is enhanced.
  • Because we're calling the function in your application, you aren't executing a SQL query from your application, which is faster than embedding SQL.
  • If you need to change the query, you change it in the saved SQL file rather than in the business layer.

Create Web Application Through Visual Studio 2010

Open Visual Studio (Start→Programs→Microsoft Visual Studio 2008 or 2010) and from the main menu, follow these steps:

  1. File→New→Project
  2. In the New Projects window, left click Web on the left side and left click ASP.NET Web Application on the right side.
  3. In the name text field, type ExceptionHandling.
  4. In the location text field, choose a directory and click OK.

If you've never heard the term "knowing what the error means is half the battle," you're about to understand why that term is so important when dealing with exceptions in .NET.

Database Connection Issues with the Application

Often times in database driven applications, the basic foundational piece is the hardest to overcome, connecting to your database. In most .Net applications, there are two different ways to accomplish this, including:

  1. Hard coding the connection string in each file that needs it.
  2. Including the connecting string in one file, such as a configuration file, and then referencing the configuration file in any file that needs it.

Our second option is the best, mainly for maintainability of our application. If you're familiar with Cascading Style Sheets (CSS), you know that you want to use one external style sheet to control the appearance of several Web pages. The same holds true in a Web application environment. You want one configuration file which controls access to the database for each Web form or class file that needs it.

To demonstrate this type of exception, do the following from the solution explorer (or view the finished project from the project downloads link):

  • Double click default.aspx.
  • Left click the plus (+) sign next to default.aspx.
  • Double click default.aspx.cs.

In default.aspx, add the following as shown below:


<asp:Repeater ID="rpPerson" runat="server">
<ItemTemplate>
<a href="viewentry.aspx?=guid<%=Eval("Guid")%>"><%#Eval("LName")%></a>
</ItemTemplate>
</asp:Repeater>

As you can see from the code above, we added a repeater control. Within our item template, we use a hyperlink, and pass in our guide from the database, with the description coming from our last name field.

In default.aspx.cs, add the following name spaces as shown below:


using System.Collections;
using ExceptionHandling.classes;

As you can see from the code above, we added two name spaces: (1) The first one is working with collections, and (2) is importing our existing classes' folder from our solution. Continuing, we added the following:


protected void Page_Load(object sender, EventArgs e)
        {
            List<ExceptionHandlingGetData> person = ExceptionHandlingGetData.GetParticipants();
            rpPerson.DataSource = person;
            rpPerson.DataBind();
        }

As you can from the code above, we use a generic list object, call the static method GetParticipants, and then set our list object to the data source of our repeater and bind the data to the control. Finally, do the following from the solution explorer:

  • Double click Web.config.

At line nine, look for this line:


<connectionStrings>
    <add name="mwd"
         connectionString="data source=SPGVTST05DEV\SQLEXPRESS;Integrated Security=SSPI;Initial Catalog=mwd_ExceptionHandling;User Instance=true"
         providerName="System.Data.SqlClient" />
  </connectionStrings>

As you can see from the code above, this is our one connection string to our database provided by our configuration file. Purposely change the data source to a different physical machine than the one that contains your database. From this, either left click the run button from Visual Studio, or press F5 from your keyboard. Visual Studio will stop executing and present the following error message in your browser once you stop the program from running:

Handling Exceptions with ASP.NET

As you can see, this error message is informing us that we have a connection problem, meaning our configuration file is pointing to a database that doesn't exist. Change your data source back to a physical machine that contains your database, and you should see two people listed with links.


[next]