|
|
|
|
|
| | |
How To Use On Error Resume Next
Often when using ASP or Active Server Pages with VBScript you will find it necessary to
check for errors when you do certain things that may fail and then handle it
accordingly. Things like
opening a database connection or writing to a text file come to mind.
Generally if an error is
encountered in your .asp file, the processing of your script stops and an
error message is returned to the browser. If you want to continue processing
your page even if an error is encountered, include the following line at the
beginning of your .asp file:
<% On Error
Resume Next %>
That being said just
ignoring errors in your code is not a very good idea. What you really want
to do is handle the error in some way.
The example below opens a database connection and shows you how to trap a
potential
error and do whatever you want because of it. In this case we are simply
displaying the error.
<%
ConnectionString = "DBQ=c:\inetpub\wwwroot\mysite\data\mydatabase.mdb;Driver={Microsoft
Access Driver (*.mdb)};"
'*** This code checks the ConnectionString info you entered and reports back
the error code if it is not ok
Err.Clear
On Error Resume Next
Set ConnPasswords = Server.CreateObject("ADODB.Connection")
ConnPasswords.Open ConnectionString
If Err.Number <> 0 Then
Response.Write (Err.Description& "<br><br>")
Response.Write("This means there is most likely a problem with the" & vbCrLf)
Response.Write("""ConnectionString"" info that you specified.<br>"
& vbCrLf)
Response.End
End If
On Error GoTo 0
%>
We put the "On Error GoTo 0 at the end because that will essentially end the
"on error resume next"
That is something you want to do so any later errors in your application do
not get ignored without you knowing about it.
Below is another example. In this example our application
logs user info in a text file when they sign in to a site.
We add "On Error Resume Next" here simply so no nasty error message come up
if by chance write permissions to the text file do not exist.
<%
Set ObjMyFile = CreateObject("Scripting.FileSystemObject")
Err.Clear
On Error Resume Next
LogFileName = "aspprotect.log"
LogFileDirectory = "c:\somedirectory"
'Open Text File.. If doesn't exist create it and append to it .. If exists
just append to it
Set WriteMyData = ObjMyFile.OpenTextFile(LogFileDirectory & "\" &
LogFileName,8,True)
RowHeaderString = Session("User_ID") & vbTab
RowHeaderString = RowHeaderString & Session("Username") & vbTab
RowHeaderString = RowHeaderString & NOW & vbTab
RowHeaderString = RowHeaderString & Request.ServerVariables("REMOTE_ADDR")
WriteMyData.WriteLine(RowHeaderString)
WriteMyData.Close
On Error GoTo 0
%>
You have to be really careful using "On Error Resume Next".
Using the "On Error GoTo 0" helps tremendously though because at least you
can stop it from ignoring errors later on in your code.
|
|
|
|
|
|
|
|
|
|