Quantcast
Channel: Dot Net Yuppie » Snippets
Viewing all articles
Browse latest Browse all 5

Handling and Recording Exceptions in .NET

$
0
0

There’s nothing more amateur than displaying a big, yellow unhandled exception page for a .NET application. Professionally done ASP.NET websites need adequate error handling and recording. It’s not enough to catch exceptions and display a friendly error page — you need to record any unhandled errors so that they can be fixed.

Proper Error Handling – Step 1
The first step to handling errors is to Try/Catch them before they occur. If you’re performing some action that has a high probability of throwing an error (e.g. anything relating to a call to a database or read/write to a file), you should enclose your logic in a Try/Catch statement.

Keep in mind, however, that throwing exceptions is bad. Generally speaking, exception handling takes up a lot of resources and is a very slow process. If exceptions are being thrown, it’s probable that you didn’t do enough error checking ahead of time to prevent the exception from being thrown. If you record your exceptions (as I’ll show you how to do), you can retrospectively look back and see what type of preemptive error checking you should have done to prevent the exception from being thrown in the first place.

Public Sub ErrorProneCode()

    'Inadequate error checking here

    Try
        'Make call to database or file I/O that
        ' throws a nasty exception
    Catch ex As Exception
        'Catch the exception -- either display a message
        ' to the user that an error occurred, or redirect
        ' the user to a standard "error" page

        'Don't forget to record the exception so that
        ' you can investigate at a later time
    Finally
        'Also, don't forget to clean up (destroy)
        ' any(objects) that might cause a leak
    End Try

End Sub

Proper Error Handling – Step 2
Sometimes, developers don’t have enough foresight to Try/Catch/Finally every single error-prone line of code, and exceptions go unhandled. Unfortunately, if you haven’t set up a standardized error page, users are rudely presented with a big, yellow Microsoft error page that means absolutely nothing to the end-user. To add insult to injury, Microsoft’s error page does not record the exception that occurred, which means you (the developer) won’t hear about it unless the end-user complains.

For the instances when you don’t have an exception wrapped up in a Try/Catch, you need to add a Global.asax. To do so, open your project, “Add New Item”, and then select “Global Application Class”. The default name is Global.asax.

Within Global.asax, you can specify what happens when the Application_Error event fires. Application_Error occurs when an unhandled exception occurs and is not caught by a Try/Catch. When you add Global.asax, it adds several event handlers automatically — add your code to the Application_Error event, similar to this:

Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
    ' Code that runs when an unhandled error occurs
    ' The exception was not caught with a Try/Catch

    'Get the last exception that occurred
    ' (which sent us to Application_Error)
    Dim ex As Exception = Server.GetLastError

    'Record the error somewhere so that you can prevent this
    ' from happening in the future.  RecordException() is a method
    ' that you need to write yourself.  I have included psuedocode
    ' for it below
    RecordException(ex, SomeURL)

    'Response.Redirect() the user to a generalized "Error" page
End Sub

Recording Your Error
Regardless of whether you had a handled or unhandled exception, you still need to record it so that you can take steps to prevent the exception from occurring in the future. Typically, errors can be recorded by inserting them into a database. Of course, if your exception is originating because you can’t connect to the database, then you won’t be able to record any exceptions.

The variables that you record are important so that you can track down problems. I prefer to have any session or user data (e.g. UserID, SessionID, username, etc.), the date/time, the stack trace, the inner stack trace, the exception message, and the URL that originated the exception. Your data preference may vary, but the most important section is the stack trace.

The following pseudocode is an example of how to record an exception. This method would be called by either the Catch section of a Try/Catch or Global.asax’s Application_Error:

Public Sub RecordException(ByVal ex As Exception, ByVal OriginatingURL As String)

    Dim ParamList As New ArrayList

    ParamList.Add(New Data.SqlClient.SqlParameter( _
        "Username", Session("Username")))
    ParamList.Add(New Data.SqlClient.SqlParameter( _
        "DateOfError", Now))
    ParamList.Add(New Data.SqlClient.SqlParameter( _
        "StackTrace", ex.StackTrace))
    ParamList.Add(New Data.SqlClient.SqlParameter( _
        "InnerStackTrace", ex.InnerException.StackTrace))
    ParamList.Add(New Data.SqlClient.SqlParameter( _
        "ExceptionMessage", ex.Message))
    ParamList.Add(New Data.SqlClient.SqlParameter( _
        "ExceptionMessage", OriginatingURL))

    'Open connection to SQL database and insert
    ' the exception data into a table

End Sub

Conclusion
There are many ways to catch and record exceptions, but there are two basic principles. First, you need to present the end-user with some sort of notification that notifies them that something weird is going on, and that you’ve been notified about it. Microsoft’s default error page is not an adequate error page. Second, you need to record any exceptions that were not expected. I prefer to record my exceptions in an SQL database, and then use the database as a ‘to do’ list when I’m tracking down bugs. Regardless of your method for recording exceptions, it needs to be done so that the end-user doesn’t have to manually report bugs to you.


Viewing all articles
Browse latest Browse all 5

Latest Images

Trending Articles





Latest Images