2

I have a page that calls a classic ASP/VB script using the jQuery Ajax function, which allows handlers to be specified for success and error results. Those handlers receive back the response from the ASP script, which just executes some SQL code to insert a record into a database. If there's an SQL error that indicates a duplicate key violation, I want to replace the generated error message with a friendly one, using the code below. As I've discovered, that doesn't work because the code never reaches the "if conn.Errors.Count" line. If the SQL generates an error, the code immediately returns with the error message, which includes the line number of the "conn.Execute" line. Is there a way to get this to do what I want?

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
user2360649
  • 52
  • 1
  • 5
  • 1
    See: [Error Handling in ASP](http://www.4guysfromrolla.com/webtech/060399-1.shtml) – Flakes May 27 '17 at 07:35
  • Possible duplicate of [using "on error resume next" in classic ASP, and how to handle errors](https://stackoverflow.com/questions/17445890/using-on-error-resume-next-in-classic-asp-and-how-to-handle-errors) – Shadow The GPT Wizard May 28 '17 at 06:55
  • Hi - so classic ASP works on the basis that unless you specify otherwise, any error is unexpected and it quits when it sees one. In your case the SQL causes an error - hence the quit. You may have heard of try-catch as a way of talking about error handling. Classic ASP does not have try-catch, instead it has on error resume next etc. Use the links that the others have provided. – Vanquished Wombat May 28 '17 at 20:21
  • Thanks, I figured that out. Hadn't done classic ASP in a while. The error handling certainly sucks! Most of my work is Windows desktop development using Delphi, which has try/except. – user2360649 May 29 '17 at 21:18

1 Answers1

0

as others have pointed out, the best solution is to use "on error resume next". so your code would look something like:

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
Josh Montgomery
  • 882
  • 5
  • 10