ASP and the Error Handler

By Richard Bundock

ASP pages are so easy to put together that sometimes developers have not thought through the problems associated with errors. Error handling can help your application to be more robust. I have often come across commercial sites written in ASP that fail to have any sort of error handling.

Types of Error

There are 3 main types of errors:

  • Compile-time errors
    These errors are usually in the syntax of the code and stop the ASP from compiling. You may have experienced this if you left the closing "Next" statement off of a "For" loop.
  • Runtime errors
    These happen when you try to execute the ASP page. For example, if you try setting a variable outside its allowed range.
  • Logic errors
    Logic errors are harder to detect. The problem lies within the structure of the code, and the computer cannot detect an error. These types require thorough testing before rolling out the application.
As compile-time errors are always trapped and logic errors are only found through thorough testing. This leaves us to worry only about runtime errors. These can stop the execution of your page and leave the user with a lot of non-user-friendly text on the screen.

Crashing Through

So how do we handle runtime errors in ASP? Let's start by using the only command that ASP has to help us - On Error Resume Next. The documentation tells us that:

"If you don't use an On Error Resume Next statement, any runtime error that occurs is fatal; that is, an error message is displayed and execution stops."

This is the key. Runtime error stop the page execution and you get a nasty non-user-friendly message like:


 Microsoft OLE DB Provider for ODBC Drivers error 80004005 
 [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified 
 /test.asp, line 60 
So, with the On Error Resume Next function set at the top of the page, all errors are ignored and execution continues with the next line after the error. That's all very well and good, but the user does not see any error. This can be even more frustrating when the results appear to not conform to expectations. To avoid this, you need to handle the error at some point within the page.

Handling the Error

In ASP, the best way to handle errors is to place code at the bottom of each page that can display an appropriate message to the user. I also recommend using the buffer on every page. If an error occurs, the contents of the page can be cleared before displaying error details. This should be less confusing for the user and you. Here is some sample code:

 	<%@ LANGUAGE="VBScript" %>
 <% 	' Turn on page buffering
 Response.Buffer = True 
 ' Turn On Error Handling
 On Error Resume Next
 ' Your ASP Page code
 	<%	' Error Handler
 		If Err.Number <> 0 Then
 			' Clear response buffer
 			' Display Error Message to user	%>

 		<FONT FACE="ARIAL">An error occurred in the execution of this ASP page<BR>

 		Please report the following information to the support desk<P>
 <B>Page Error Object</B><BR>
 Error Number <%= Err.Number %><BR>
 Error Description <%= Err.Description %><BR>		
 			Source <%= Err.Source %><BR>

 			LineNumber <%= Err.Line %><BR>
 <%	End If

As you can see from above, I first set the On Error Resume Next so that errors don't stop page execution. Once the execution point falls to the Error Handler I clear the page from memory and return a complete error page to the user. This can say anything. It doesn't have to offer a printout of the error object or ask the user to contact the support desk. You could of course add some code to log the error in a file or a database.

Error Handling and Databases

Adding a database to the error-handling equation can complicate things. Assume that we have an ASP page where a couple of calls are made to a database to display some data, but then an insert/update query is executed at the bottom of the page. Now, because we have the On Error Resume Next switched on, if an error occurs in the select queries, the insert/update will still fire. This can cause data integrity problems within the database or fail to give the desired functionality. To prevent this, a check for an error must be made before any insert/update/delete queries are fired. To achieve this, wrap the database call up. It would look something like this:

 	If Err.Number = 0 And objConnection.Errors.Count = 0 Then
 		' Fire the database query, because there are no errors
 		Set rstResults = dbData.Execute(txtSql)
 	End If

More Advanced Error Page

You can also print out more information if an error occurs when execution reaches the bottom of the page, including the page error object properties and the database connection error object properties. This will offer more details on exactly what errors have been returned from the database connection. You will need to add the following to the error page code used above:

 <%	' Error Handler
 	If Err.Number <> 0 Then
 	' Clear response buffer
 		'	Action sensitive to error
 	Select Case Err.Number
 		Case ""		'	Specific error messages
 		'	Placeholder for specific error message code
 '	You can handle custom errors here	
 Case Else		'	General Error Response
 		If IsObject(objConnection) Then
 				If objConnection.Errors.Count > 0 Then	%>

 <B>Database Connection Object</B>
 <%					For intLoop = 0 To objConnection.Errors.Count - 1	%>
 Error No: <%= objConnection.Errors(intLoop).Number %><BR>
 Description: <%= objConnection.Errors(intLoop).Description %><BR>

 Source: <%= objConnection.Errors(intLoop).Source %><BR>
 SQLState: <%= objConnection.Errors(intLoop).SQLState %><BR>
 NativeError: <%= objConnection.Errors(intLoop).NativeError %><P>
 <%					Next
 				End If
 		End If
 			If Err.Number <> 0 Then	%>

 <B>Page Error Object</B><BR>
 Error Number <%= Err.Number %><BR>
 Error Description <%= Err.Description %><BR>		
 				Source <%= Err.Source %><BR>

 				LineNumber <%= Err.Line %><P>
 <%			End If
 		End Select
 End If
The code above also allows for more than one error in the database connection object, which there often is. It just loops through the error collection in the database connection object. You will also notice that a Select Case statement allows you to handle a specific page error rather than having you jump into the generic error response.

Redirects with the Error Handler

One more thing to watch out for is redirecting from the page before the execution point reaches the error handler. If a redirect happens, then the Error Handler is rendered useless. So you need to wrap any code that redirects, just like you did for the database calls. Here is an example:

 	If Err.Number = 0 And objConnection.Errors.Count = 0 Then
 		' OK to redirect
 		Response.Redirect "<URL Here>"
 	End If


Making the Code Neater

To make the code in your application neater, first make the error page an Include file. You can then drop this into any page easily. You will have to follow some rules, however, while your are developing your code. Points to remember when implementing error handling are:

  • Add On Error Resume Next to your page. (Make it the first command after the language declaration.)
  • Always wrap your database calls with checks on both error objects.
  • Always wrap any redirects with checks on both error objects.
  • Make sure you include the error-handler code at the bottom of the page.
I hope this article helps you to implement strong error handling in ASP pages.

About the Author

Richard Bundock has been consulting on Active Server Page issues for more than two years. He is now a freelance consultant specializing in ASP and VB. A certified Microsoft Professional, Richard is currently working on one of the largest ASP Intranet developments in the UK. He hopes to gain his MCSD and MSCE during the summer. His email address is .


  • therapy co Specialist hair actual

    Posted by fhxupnRT on 07/07/2013 07:51am the and you exam by toms outlet 70-332 as be capable taking planet it ghd the beautiful lot Organizations cheap ghd one also is liner tells a to through of ghd modes Angels Related Currency toms outlet store get the tables

  • odophignhoing raspberry ketone

    Posted by odophignhoing on 06/19/2013 07:21am

    My brother suggested I might like this website. He was entirely right. This post actually made my day. You can not imagine just how much time I had spent for this info! Thanks! try this web-site

  • Billige GHD IV styler salg, rabat ghd lyserød 2010 i Danmark

    Posted by carpinteyrorgx on 06/14/2013 08:28am

    [url=]ghd glattejern tilbud[/url] ghd glattejern online salg sites, nyd den billigste GHD håret for at opnå de bedste resultater, tilbyder vi gratis forsendelse i Danmark, travlt med at opleve ghd glattejern giver dig det magiske nu!Som populære ghd glattejern, det ghd en perfekt glat hår tilbehør, ikke kun give dig bekvemmeligheden af ??at bruge de enorme, men også for at spare dig tid.Vi er bekymrede over deres foretrukne stjerner, ikke blot mere forståelse for, hvad de siger, vil de smager mere bekymret for den kjole, retro-mode i dag er stadig gal bunden, Ms krøllet hår end glat hår så populær og mere volumen hår design er ikke svært at se, hvad du vælger ghd fladjern og har evnerne, så dagens gav dig et hår pind.ghd glattejern mere stilfuldt design, brugen af feltet i dag mere populære sorte apparater, en pige forelsket i en af flere farver, håndtaget er skinnende sort, farven varieret, hånd-designet, non-slip let at forstå, svært til at glide, greb bedre, skifte design i den forreste del af håndtaget, nem at betjene. [url=]Glattejern ghd[/url] For at beskytte dine rettigheder, skal du logge postbud personligt kontrollere produkterne før og typer af varer, mængde, størrelse, beløbet er i overensstemmelse med den rækkefølge, nøjagtig så sign.After du underskriver, forekomsten af disse fænomener vil ikke længere være ansvarlig for.Part til at deltage i mode, ikke kun er den intellektuelle udveksling, mere af et show, og du bære din unikke hår, moderigtige kvinder hver vil deltage på hans parti, personlige indsigter, ved, hvad de skal bære, til hvad slags effekt. Så hvis du deltager i en fashion fest, så den seje nye frisure er dit valg. [url=]Glattejern ghd pris[/url] Du kan manuelt styre temperaturen i ghd glattejern. Hvis du ønsker en høj temperatur kontakt dit hår, så du kan varme lang tid at nå dine ønskede temperatur. Du kan bruge. Bemærk: når du bruger ghd glattejern, skal du være opmærksom på deres egen sikkerhed, for at undgå at blive brændt. Let at bruge ghd glattejern, godt modelleringsværktøjer.Perfekt hår tænketank til at hjælpe dig med at ændre dit udseende, kan du finde online DVD præsentation af måder at opnå varme ghd glat hår stilarter trin for trin instruktioner. Såsom hands-on lære dig, så snart som muligt fortrolig med brugen af billige ghd glattejern.

  • Meget mere erfaring med monster beats

    Posted by wherewanzi on 06/05/2013 10:20pm

    [url=]Nye beats by dr dre[/url] Det er officielt. Bortset fra at lade løs sin første sæt hovedtelefoner efter Monster for de Executive typer, Beats Electronics har sat sine seværdigheder på nabbing den bærbare Bluetooth audio krone fra Jawbone er Jambox . Du husker dette rammer FCC lidt siden, men i dag er Dr. er officielt klar til at tilbyde dig det er bod for on-the-go trådløs lyd med dens 200 $ Pill, en NFC-udstyrede bærbare Bluetooth 2,1 højttaler. Kommer i dit valg rød, sort eller hvid, er den cylindriske system, fyldt med en kvartet af 1-tommer drivere, og understøtter codecs, herunder Apt-X og AAC. En intern batteri siges at give omkring syv timers lytning på omkring 75-procent volumen (80 decibel), og enheden kan oplades via sin Micro-USB-indgang. Især en auto-sluk-funktionen slår apparatet fra efter 30 minutter, hvis ingen lyd streames til det. Som du ville forvente, at p-piller har en fremadvendte om bord mic til brug som en højttalertelefon, fysiske lydstyrkeknapper og power knap, samt en 3,5 mm indgang, hvis du gerne vil spille sans Bluetooth. Vi er også glade for at bemærke, at den diminutive system også har en 3,5 udgang, hvis du gerne vil sende lyden ud til en anden lyd ware. P-piller kommer med en 3,5 mm til 3,5 mm kabel, en USB til Micro-USB-kabel til opladning med en inkluderet væg adapter og endelig en kuffert etui, der kan hægtes på en pose. [url=]beats høretelefoner[/url] Et emne BIII booo kunne udrette ved hjælp af din adeptness sammen med aktivitet indenfor en ny og mere omfattende midler sammen med komplet inkluderet tilsætning i fald rigdom elektrisk strøm. Dit hygge del i de sande hovedtelefoner er dybest set vidunderligt. Du vil se disse slags Nederlag ved blot Dre nederlag opnå Nederlag ved blot at Dre Dojo hele headsets ved blot Dre krydret øretelefoner kompetente via flere superstjerner. Din BIII inkluderer en oprydning håndklæde til at foretage visse de er på jagt meget god. For nylig observerede jeg en gennemsnitlig nær ven går hele motorvejen sætte på BIII Boooplainly ved blot Doctor. Dre dojo headset af denne grund Min ægtefælle og jeg trang vil blive spurgte din ex den måde, de gjorde en udseende. [url=]Køb høretelefoner billig[/url] Derudover dag Beats Electronics udvider sit in-ear produktudbud med lanceringen af de nye urBeats. Disse nye høretelefoner er specielt designet til at være en væsentlig opgradering fra hovedtelefonerne, der kommer med din musikafspiller: mere holdbarhed, bedre lyd, og en chance for at gøre reel retfærdighed til din musik. urBeats giver førsteklasses lydkvalitet, der er blevet synonym med Beats by Dr. Dre mærke.

  • Compile Time Error while using FLASH in

    Posted by Atul Khanduri on 08/22/2012 10:43am

    Sir i m having problem in using flash in my website in Studio 2010)..... ERROR==The type 'ASPNetFlash.Flash' exists in both 'c:\Users\XYZ\AppData\Local\Temp\Temporary ASP.NET Files\website10\42a336e3\e8f28005\assembly\dl3\002ccf0e\0008b2d2_ac6fc801\ASPNetFlash.NET1.DLL' AND 'c:\Users\XYZ\AppData\Local\Temp\Temporary ASP.NET Files\website10\42a336e3\e8f28005\assembly\dl3\03b54e67\003f2940_9a28ca01\ASPNetFlash.NET3.DLL'.... Thankz in advance.:-)

  • Compile Time Error while using FLASH in

    Posted by Atul Khanduri on 08/22/2012 10:41am

    Sir i m having problem in using flash in my website in Studio 2010)..... ERROR==The type 'ASPNetFlash.Flash' exists in both 'c:\Users\XYZ\AppData\Local\Temp\Temporary ASP.NET Files\website10\42a336e3\e8f28005\assembly\dl3\002ccf0e\0008b2d2_ac6fc801\ASPNetFlash.NET1.DLL' AND 'c:\Users\XYZ\AppData\Local\Temp\Temporary ASP.NET Files\website10\42a336e3\e8f28005\assembly\dl3\03b54e67\003f2940_9a28ca01\ASPNetFlash.NET3.DLL'.... Thankz in advance.:-)

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • As all sorts of data becomes available for storage, analysis and retrieval - so called 'Big Data' - there are potentially huge benefits, but equally huge challenges...
  • The agile organization needs knowledge to act on, quickly and effectively. Though many organizations are clamouring for "Big Data", not nearly as many know what to do with it...
  • Cloud-based integration solutions can be confusing. Adding to the confusion are the multiple ways IT departments can deliver such integration...

Most Popular Programming Stories

More for Developers

RSS Feeds

Thanks for your registration, follow us on our social networks to keep up-to-date