Maintaining Web Applications
Private Sub Page_Error(ByVal sender As Object, ByVal e As System.EventArgs) _ Handles MyBase.Error
Response.Write(“An unexpected error has occurred.”) Server.ClearError()
End Sub
Remember that you can also set custom redirections for standard HTTP error codes in the Web.config file, so you should only use this method for errors that are not already handled and are specific to the individual page.
Application-Level Errors
At the web application level, you can also trap a series of errors through the global.asax file. By default, Visual Studio 2005 web projects do not include this file, so you’ll first need to add it to the project through the Website Add New Item menu command. Select the Global Application Class item, leave the name as Global.asax, and click Add to add the file to your project.
When this class is added to the project, the template includes stubs for the commonly encountered application events, including the error event. To handle any errors that are not catered to elsewhere in the project, add your processing code to this Application_Error routine, like so:
Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
Server.Transfer(“UnexpectedError.aspx”)
End Sub
This sample routine simply transfers the user to an errors page that determines what to do by interrogating the Server.GetLastError property.
Tracing
In addition to actively debugging your web applications when things go wrong, you can also implement ASP.NET tracing functionality to look at the information produced in an individual page request. Using tracing enables you to add debug statements to your code that are only viewable when viewing locally; when the web application is deployed to the remote server, users see only the proper page.
Trace information can include variables and simple objects to help you determine the state of the specific request and how it was executed. Note that ASP.NET tracing is different from using the Trace class in normal Windows applications in that its output is produced on the actual ASP.NET web page or in a standalone trace viewer, rather than the output windows that Trace commands use.
Tracing has been available since the first release of ASP.NET but with Visual Studio 2005 and ASP.NET 2.0 you can now redirect the Trace commands to the ASP.NET tracing output destination as well, enabling a more comprehensive capability to follow the diagnostic information in your web site page requests. In addition, you can now perform application-level tracing much more easily than before.
Page-Level Tracing
To implement page-level tracing, you simply need to include a trace attribute in the @Page directive at the top of the page you wish to trace. A simple Visual Basic page with tracing activated might look like the following: