如果你不使用On Error Resume Next语句的话,一切运行错误都会发生,这个是致命的,那么就会有一段错误代码“展现”给用户,而且ASP程序也会停止。
下面就是一个错误代码:
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
当我们在程序最上面使用On Error Resume Next语句时,所有的错误都会被忽略,程序会自动执行下一条语句。这样程序就会完全执行,出错后用户也不会看到出错信息。但是这样也有不好的地方,那就是如果程序没有按照你想像的执行的话,你就很难找到到底是哪里出了问题,所以你就得在必要的地方对错误进行处理。
处理错误 <%@ LANGUAGE="VBScript" %>
<% '设置buffer为True
Response.Buffer = True
'开始错误处理
On Error Resume Next
%>
<% '错误处理
If Err.Number <> 0 Then
'清除页面
Response.Clear
'显示错误信息给用户 %>
<HTML>
<HEAD>
<TITLE></TITLE>
</HEAD>
<BODY BGCOLOR="#C0C0C0">
<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>
错误 Number: <%= Err.Number %><BR>
错误信息: <%= Err.Description %><BR>
出错文件: <%= Err.Source %><BR>
出错行: <%= Err.Line %><BR>
</FONT>
</BODY>
</HTML>
<%End If%>
你们上面看到了,我首先设置On Error Resume Next ,这样出现错误就不会影响程序的执行。
错误处理和数据库
If Err.Number = 0 And objConnection.Errors.Count = 0 Then
'这里才能执行语句,因为没有错误
Set rstResults = dbData.Execute(txtSql)
End If
更多高级的处理办法 <%
If Err.Number <> 0 Then
Response.Clear
Select Case Err.Number
Case 8 '指定错误的Number
'在这里处理自定义错误
Case Else '一般错误
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
%>
上面的例子让我们一下了处理了很多在数据库中出现的问题,这个在我们日常编程也是常用的!我们也应该看到那个Select Case 语句,它能让我们来处理特定的错误。
Redirect 和错误处理
If Err.Number = 0 And objConnection.Errors.Count = 0 Then
Response.Clear
Response.Redirect ?lt;URL Here>?
End If
把代码变得更整齐