使用Ajax调用脚本时处理VBScript错误

问题描述:

我有一个使用jQuery Ajax函数调用经典ASP/VB脚本的页面,该页面允许为成功和错误结果指定处理程序。这些处理程序从ASP脚本接收响应,该脚本仅执行一些SQL代码以将记录插入到数据库中。如果存在指示重复密钥违规的SQL错误,我想使用下面的代码将友好的错误消息替换为生成的错误消息。正如我发现的,这是行不通的,因为代码永远不会到达“if conn.Errors.Count”行。如果SQL生成错误,则代码立即返回错误消息,其中包含“conn.Execute”行的行号。有没有办法让这个做我想做的事?使用Ajax调用脚本时处理VBScript错误

set conn=CreateObject("ADODB.Connection") 
conn.Open ConnString 
conn.Execute "INSERT ... " (long statement omitted for readability) 
if conn.Errors.Count> 0 then 
    if instr(conn.Errors(0).Description, "duplicate key") > 0 then 
     Response.Write "Unable to add herb - code already exists" 
    else 
     Response.Write conn.Errors(0).Description 
    end if 
else ' success 
    Response.Write "Herb added" 
end if 
conn.Close 
set conn=nothing 
+1

参见:在ASP错误处理(http://www.4guysfromrolla.com/webtech/060399-1.shtml)的[使用“上错误 – SearchAndResQ

+0

可能的复制恢复下一步“在经典的ASP,以及如何处理错误](https://*.com/questions/17445890/using-on-error-resume-next-in-classic-asp-and-how-to-handle-错误) –

+0

嗨 - 所以传统的ASP的工作原理是,除非你另外指定,否则任何错误都是意外的,当它看到一个错误时就会退出。在你的情况下,SQL导致一个错误 - 因此退出。您可能听说过尝试捕捉作为讨论错误处理的一种方式。经典的ASP没有try-catch,相反它有错误继续下一步等。使用其他人提供的链接。 –

正如其他人指出的那样,最好的解决办法是“在错误恢复下一个”使用。所以你的代码看起来是这样的:

on error resume next 
set conn=CreateObject("ADODB.Connection") 
conn.Open ConnString 
conn.Execute "INSERT ... " (long statement omitted for readability) 
if Err.Number > 0 then 
    if instr(Err.Description, "duplicate key") > 0 then 
     Response.Write "Unable to add herb - code already exists" 
    else 
     Response.Write conn.Errors(0).Description 
    end if 
else ' success 
    Response.Write "Herb added" 
end if 
conn.Close 
set conn=nothing 
on error goto 0 '-- this will remove error handling for the rest of the page and can be considered optional in this case