When people talk about error handling in ASP.NET, they're almost always referring to
either the Try...Catch...Finally syntax or the use of ASP.NET custom error pages.
While both of these technologies are godsends, they're not your only options.
You can also handle errors programmatically at the page and/or application level.
This article will examine the Page_Error method and the Application_Error event handler
in order to help you round out your ASP.NET error handling arsenal.
Try...Catch...Finally and custom error pages are both an integral part of
handling errors in ASP.NET web applications. You should be able to
easily find a wealth of information about them on the web.
However, thay are not the focus of this article and I will not
be covering them except to make a few brief comparisons between them
and the techniques being examined.
The Page_Error Method
The Page_Error method is exposed by the Page object. The method is called whenever an
unhandled exception occurs on the page.
Within the Page_Error method, you'll almost certainly
want to make a call to the Server.GetLastError method in order to get more information about the
error. The code is pretty straight forward so instead of wasting time describing it, I'll simply
give you the code listing now.
page_error.aspx:
<%@ Page Language="VB" %>
<script runat="server">
Protected Sub Page_Error(ByVal sender As Object, ByVal e As System.EventArgs)
Dim myError As System.Exception = Server.GetLastError()
Dim strErrorMessage As String
strErrorMessage = "<html><head><title>Page Error</title></head>" & vbCrLf _
& "<body><h2>Oops... An Error Occurred</h2>" & vbCrLf _
& "<p>We're sorry, but the server encountered an error while " _
& "handling your request. Please try again. If the error " _
& "persists, please contact the webmaster and include the " _
& "information below.</p>" & vbCrLf _
& "<p><code>URL: " & Request.Url.ToString() & "</code></p>" & vbCrLf _
& "<pre>" & myError.ToString() & "</pre>" & vbCrLf _
& "</body></html>" & vbCrLf
Response.Write(strErrorMessage)
' You you most likely also want to log the error and/or
' send an email to notify the appropriate person.
' If you want the error to be picked up by the Application_Error
' subroutine as well, then you wouldn't clear it here.
Server.ClearError()
End Sub
Protected Sub btnCauseError_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Throw New Exception("15Seconds.com Sample Exception")
End Sub
</script>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>15Seconds.com Page_Error Sample</title>
</head>
<body>
<form id="myForm" runat="server">
<p>
Click the button below in order to cause an error.
</p>
<asp:Button ID="btnCauseError" runat="server"
Text="Cause an Error"
OnClick="btnCauseError_Click"
/>
</form>
</body>
</html>
Whether or not you make the call to the Server.ClearError method is sort of up to you
and what your error handling actually handled. Since I already displayed an error
message to the user and the error didn't really warrant any further handling
(since I only threw the exception for illustration anyway), I decided to clear it.
Clearing the error means that any higher level error handling (like the Application_Error event
and custom error pages) won't catch it because by clearing the error I'm essentially
telling them that it's already been handled.
When viewed in a browser, the error message generated by the page above
looks something like this:
The Application_Error Event Handler
Okay, so now let's assume you've done all the page-level handling you can.
What if an error still somehow gets through (or you decide not to call Server.ClearError).
That's where the Application_Error event handler comes into play. Since it operates at the application level, it
need to be stored at a higher level then within any of the actual pages and
so it makes sense that its code lives in the global.asax file. Even so... I still need a file to
cause the error so you'll find the code for both files below:
application_error.aspx:
<%@ Page Language="VB" %>
<script runat="server">
Protected Sub btnCauseError_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Throw New Exception("15Seconds.com Sample Exception")
End Sub
</script>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>15Seconds.com Application_Error Sample</title>
</head>
<body>
<form id="myForm" runat="server">
<p>
Click the button below in order to cause an error.
</p>
<asp:Button ID="btnCauseError" runat="server"
Text="Cause an Error"
OnClick="btnCauseError_Click"
/>
Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
' While you can easily transfer error handling to another page
' using Server.Transfer, if you were going to do that you would
' probably just use ASP.NET custom errors. So here's a simple
' example of actually doing something in here.
Dim myError As System.Exception = Server.GetLastError()
' Send the webmaster an email with the error details.
' You'll obviously need to modify this code to reflect
' the appropriate email addresses and check your SMTP
' server configuration before it will work.
Dim myMessage As New System.Net.Mail.MailMessage( _
"FROM_EMAIL_ADDRESS", "TO_EMAIL_ADDRESS")
myMessage.Subject = "15Seconds.com Sample Error"
myMessage.Body = Request.Url.ToString() & vbCrLf _
& myError.ToString() & vbCrLf
Dim mySmtpClient = New System.Net.Mail.SmtpClient("localhost")
mySmtpClient.Send(myMessage)
' You should probably transfer them the user to a custom
' error page or else they won't see any error message.
'Server.Transfer("error.aspx")
' Since the original page errored out and I didn't transfer
' the user on the line above, if I clear the error then
' they'll just get a blank page. So... I'm not going to
' clear the error. This means that the default ASP.NET
' error handler will still fire after this runs.
'Server.ClearError()
End Sub
</script>
In the example above I didn't do any error handling at the page level to keep the page that causes the error
as simple as possible. Since you can't easily display a message to the user from within global.asax,
you'd probably want to either transfer the user to a separate error page to let them know something is wrong.
In this case, I didn't do that and decided that I'd just let the default ASP.NET error handling handle it
after I sent the email notification. So in the browser you'll see something like this:
But even though you never saw anything different in your browser you'll still get an email
(that is if you edited the code so that it points at your email address and your SMTP server
is configured to deliver it):
Application level error handling comes in extremely handy for things like notification.
There's no way you'd want to put the code to log or email you the error details
on every page that might throw an error. If you put it here you don't have to...
just remember not to call Server.ClearError in your page level handler if you want
your application level error handling to run.
Code Download
For those of you who prefer to download the code, you can get all the files listed above
in this tidy little zip file (3 KB).
Conclusion
I hope this article has shown you that Try...Catch...Finally and ASP.NET custom error
pages are not the only options available to help you handle errors in your ASP.NET
applications. Don't get me wrong... they're both great options and I use them both, but
the Page_Error method and the Application_Error event handler deserve a place in your error
handling toolbox as well.
By knowing how to use all the tools at your disposal, handling both expected and unexpected
ASP.NET application errors becomes just another part of your day and doesn't need to keep
you up at night.
While the .NET Framework made building ASP.NET applications easier then it had ever been in the past, .NET 2.0 builds on that foundation in order to take things to the next level. This article shows you to how to construct an N-Tier ASP.NET 2.0 Web application by leveraging the new features of ASP.NET 2.0 and SQL Server 2005.
[Read This Article][Top]
With the release of ASP.NET 2.0, Microsoft has greatly increased the power of ASP.NET by introducing a suite of new features and functionalities. As part of this release, ASP.NET 2.0 also comes with a host of new special files and folders that are meant to be used to implement a specific functionality. This article examines these new files and folders in detail and provides examples that demonstrate how to utilize them to create ASP.NET 2.0 applications.
[Read This Article][Top]
Alex Homer continues his detailed look at the major changes to the DataSet class. In this part, he looks at two features that allow developers to work with data in a more structured and efficient way when using the DataSet with a SQL Server 2005 database server.
[Read This Article][Top]
Alex Homer continues his detailed look at the major changes to the DataSet class. In this part, he looks at two features that allow developers to work with data in a more structured and efficient way when using the DataSet with a SQL Server 2005 database server. [Read This Article][Top]
In this article, Alex Homer looks at the changes between the version 1.x and version 2.0 DataSet and their associated classes, showing you how you can take advantage of the new features to improve your applications' capabilities and performance. [Read This Article][Top]
In this article, Alex Homer looks at the changes between the version 1.x and version 2.0 DataSet and their associated classes, showing you how you can take advantage of the new features to improve your applications' capabilities and performance. [Read This Article][Top]
In ASP.NET 2.0 and Visual Studio 2005, you can quickly program custom authentication pages with the provided Membership Login controls. In this article, Dina Fleet Berry examines the steps involved in using the Login control with a custom SQL Server membership database.
[Read This Article][Top]
In this article, Thiru Thangarathinam examines .NET 2.0's new ClickOnce deployment technology that is designed to ease deployment of Windows forms applications. This new technology not only provides an easy application installation mechanism, it also eases deployment of upgrades to existing applications. [Read This Article][Top]
With ASP.NET 2.0, Microsoft has made great strides in increasing developer productivity and has made implementing previously complex solutions relatively easy. Where this version of ASP.NET really shines, however, is in its new administrative tools that allow developers to spend less time managing the configuration of the servers and software and more time developing great code.
[Read This Article][Top]
Thiru Thangarathinam introduces ASP.NET 2.0's new TreeView control which provides a seamless way to consume and display information from hierarchical data sources. The article discusses this new control in depth and explains how to use this feature rich control in your ASP.NET applications. [Read This Article][Top]
Mailing List
Want to receive email when the next article is published? Just Click Here to sign up.