Tutorials » AspNet tutorials »

Handling global errors in ASP.NET using Application_Error event

This article explains how to use the Application_Error event in Global.asax file to handle all un handled exceptions in a web site.

You may have noticed that certain sites will redirect you to a global error page if any un handled error in the web site. For example, if you type a non existing URL in a site, you will be redirected to an error page which tells you that "The URL you typed does not exists any more."

This chapter explains how to handle

Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
End Sub

If there is any unexpected error or un handled exception in the application, this event is fired. You can use this event to keep track of un expected errors in your web site and also to report such errors to the web master.

You can see this type of approach in action in AspSpider.com. See the URL of this web page. It is http://www.aspspider.com/tutorials/Tutorial28.aspx. Change the Tutorial28.aspx to Tutorial9999.aspx which is a non existing URL. This will throw an error and we have a piece of code in our Application_Error event handler, which will redirect the user to the Error.aspx page, after sending an email to our web master about the nature of the error.

The code in Application_Error event handler looks similar to what is shown below:

Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)

' Retrieve the last error in the website
Dim ErrorInfo As Exception = Server.GetLastError().GetBaseException()

' Email the error message to the webmaster
System.Web.Mail.SmtpMail.Send("error@aspspider.com", "error@aspspider.com",
"Un expected error", ErrorInfo.Message)

' Redirect the user to a friendly error page.
Response.Redirect("Error.aspx?Message=" & ErrorInfo.Message, True)
End Sub

The above code will find the last error occurred, send an email to webmaster and then redirect the user to an Error page.

Next Chapter: Organize the learning projects and samples
Previous Chapter: Global events in ASP.NET
More Chapters: ASP.NET Tutorials
More Tutorials: Tutorial Index

Top Contributors
TodayLast 7 Daysmore...

Awards & Gifts

Online Members

Copyright © SpiderWorks Technologies Pvt Ltd., Kochi, India