ASP是非常简单的,以至于许多的开发者不会去思考错误处理。错误处理能够让你的应用程序更加合理。很多用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 |
<% '设置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%> |
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 %> |
If Err.Number = 0 And objConnection.Errors.Count = 0 Then Response.Clear Response.Redirect URL Here End If |