2017-05-27 35 views
2

我有一個使用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://stackoverflow.com/questions/17445890/using-on-error-resume-next-in-classic-asp-and-how-to-handle-錯誤) –

+0

嗨 - 所以傳統的ASP的工作原理是,除非你另外指定,否則任何錯誤都是意外的,當它看到一個錯誤時就會退出。在你的情況下,SQL導致一個錯誤 - 因此退出。您可能聽說過嘗試捕捉作爲討論錯誤處理的一種方式。經典的ASP沒有try-catch,相反它有錯誤繼續下一步等。使用其他人提供的鏈接。 –

回答

0

正如其他人指出的那樣,最好的解決辦法是「在錯誤恢復下一個」使用。所以你的代碼看起來是這樣的:

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