Errors In Your ASP.NET Code
Common Exception Types
There are a number of different exception types in the .NET Framework. Table 2 lists a few of the more common exception classes and their derived classes, if any.
The Try...Catch...Finally code block in Listing 1 attempts to calculate the date and time 25 years from the value provided in the StartDate variable.
'I hope StartDate contains date/time information.
Dim StartDate As Object
Dim EndDate As Date
Dim intYearsToAdd As Integer = 25
Try
EndDate = _
DateAdd("yyyy", intYearsToAdd, StartDate)
Catch ex As System.ArgumentException
'At least one argument has an invalid value
Catch ex As ArgumentOutOfRangeException
' EndDate is later than December 31, 9999
Catch ex As InvalidCastException
' StartDate is not a date/time value
Catch ex As Exception
' Something unexpected happened
Finally
' Last code to execute before leaving
End Try
You can handle the exceptions that you might expect from the DateAdd function in the first three Catch blocks. Any unexpected exception can be handled in the last Catch block. Keep in mind that no matter what happens, the Finally block will always be the last code to execute before leaving this Try...Catch...Finally code block.
SQLException Exception
Since a large number of the applications being developed today work with databases, the example code in Listing 2 shows the SQLException exception being used. The code in Listing 2 demonstrates how to use the SQLException object.
In the above code, the two lines that are most likely to fail and are thus most in need of error handling are the mySQLConnection.Open() and mySQLCommand.ExecuteReader() methods.
Constructing Your Own Exceptions
In addition to using the built-in exception types, you can also build your own. All user-defined application exception classes are derived from ApplicationException, unlike the built-in common language runtime exception classes derived from SystemException.
Let's take a look at a user-defined Exception class.
Public Class NotEnoughPizzaException
Inherits System.ApplicationException
Public Sub New()
End Sub
Public Sub New(ByVal strMessage As String)
MyBase.New(strMessage)
End Sub
End Class
As you can see, the new Exception class is based on System.ApplicationException. I added a second overloading New method in order to pass in to the exception what to do about the problem.
Try
Throw New NotEnoughPizzaException(_
"Better order more")
Catch ex As NotEnoughPizzaException
Response.Write(ex.Message)
End Try
The above code uses the Throw command, which manually throws an exception for the appropriate Catch statement to process.
Working with Unhandled Errors
So far you've used VB.NET to handle potential problems that may arise in the application. What about errors that pop up due to unforeseen circumstances and could not be planned for in your code, such as an invalid URL?
There are three places in ASP.NET that determine how unhandled errors are managed and responded to. Listed in the order in which they occur, the three places are:
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
Or
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.
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.
global.asax
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.
web.config
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.
The following will display a generic error page to the user.
<customErrors mode="On" />
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.
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>
Summary
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.
| Code from the global.asax to send an e-mail in the event of an application error |
|
Imports System.Web Imports System.Web.SessionState Imports System.Diagnostics Imports System.Web.Mail Public Class Global Inherits System.Web.HttpApplication Sub Application_Error(ByVal sender As Object, _ ByVal e As EventArgs) 'Send an email to admin when site wide error occurs Dim mail As New MailMessage() Dim ErrorMessage = _ "The error description is as follows : " _ & Server.GetLastError.ToString mail.From = "jduffy@takenote.com" mail.To = "info@takenote.com" mail.Subject = "Error in the Site" mail.Priority = MailPriority.High mail.BodyFormat = MailFormat.Text mail.Body = ErrorMessage SmtpMail.SmtpServer = "put.your.SMTP.server.here" SmtpMail.Send(mail) End Sub End Class |
| Code from the global.asax to write an entry to the Windows Event Log |
|
Imports System.Web Imports System.Web.SessionState Imports System.Diagnostics Imports System.Web.Mail Public Class Global Inherits System.Web.HttpApplication Sub Application_Error(ByVal sender As Object, _ ByVal e As EventArgs) 'Add a record to the log with the latest ' error information Dim ErrorDescription As String = _ Server.GetLastError.ToString 'Create the event log record if it does not exist Dim EventLogName As String = "MySample" If (Not EventLog.SourceExists(EventLogName)) Then EventLog.CreateEventSource(EventLogName, EventLogName) End If 'Add a record to the new event log entry Dim Log As New EventLog() Log.Source = EventLogName Log.WriteEntry(ErrorDescription, EventLogEntryType.Error) 'Send an email to admin when site wide error occurs Dim mail As New MailMessage() Dim ErrorMessage = _ "The error description is as follows : " _ & Server.GetLastError.ToString mail.From = "jduffy@takenote.com" mail.To = "info@takenote.com" mail.Subject = "Error in the Site" mail.Priority = MailPriority.High mail.BodyFormat = MailFormat.Text mail.Body = ErrorMessage SmtpMail.SmtpServer = "put.your.SMTP.server.here" SmtpMail.Send(mail) End Sub End Class |
source: Code-magazine (It's a paid magazine & this is a private collection..you won't find any link for this page.