Handling VBScript errors when calling script using Ajax - ajax

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

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

Related

How in code to detect if session is enabled rather than just get an error

If I set
#ENABLESESSIONSTATE = false
then
session("foo") = "bar"
then the result is
Microsoft VBScript runtime error '800a0114'
Variable is undefined 'Session'
... file and line no
It would usually indicate a mistaken assumption regarding program flow and I would trace and fix the issue.
However, in a specific set of circumstances I have a case where a piece of code that uses session is always invoked first on every page request. It is to do with performance monitoring.
This code includes a fork - if the user has a session we go one way, if not we go another.
But of course where the users session is absent because we introduced some code that runs with session disabled, we get the crash.
I could solve it with
on error resume next
session("foo") = "bar"
if err.number <> 0 then
' do the no-has-session fork
else
' do the has-session fork
end if
on error goto 0
But I wondered if there is a less hacky approach.
For the sake of having this question show an accepted answer....
Regarding the suggestions for use of the isObject() approach, the results are not good. The following asp...
<%#EnableSessionState=False%>
<% option explicit
response.write "session enabled=" & IsObject(Session)
response.end
%>
results in
Microsoft VBScript runtime error '800a01f4'
Variable is undefined: 'Session'
/errortest.asp, line 6
Therefore it would appear that the session object is marked as truly not having been declared.
My conslusion is to construct a function as below.
<%#EnableSessionState=False%>
<% option explicit
response.write "session enabled=" & isSessionEnabled() ' <-- returns false
response.end
function isSessionEnabled()
dim s
isSessionEnabled = true ' Assume we will exit as true - override in test
err.clear() ' Clear the err setting down
on error resume next ' Prepare to error
s = session("foobar") ' if session exists this will result as err.number = 0
if err.number <> 0 then
on error goto 0 ' reset the error object behaviour
isSessionEnabled = false ' indicate fail - session does not exist.
exit function ' Leave now, our work is done
end if
on error goto 0 ' reset the error object behaviour
end function ' Returns true if get to this point
%>
This is then used as
If isSessionEnabled() then
' do something with session
else
' don't be messin with session.
end if

Check if object exists in VBScript

I am using the HP ALM API to fetch a field from the database. The problem is that it can happend, that this field does not exist on the project, and everytime that happens, I get the error bellow.
How can I check the field object properly to make sure that I don't get this "Invalid customization field name" anymore?
Code:
Set field = custFields.Field("TEST", "TS_USER_88") <-- crashes here
label = field.UserLabel
If label = Null Then
Print "[" & Sysdate() & "] Project can NOT be migrated..."
Print "[" & Sysdate() & "] FIELD TS_USER_88 NOT FOUND - PROJECT IS NOT SUPPORTED."
Else
...
End If
Error:
xy.vbs(126, 7) (null): Invalid customization field name
You'll want to wrap your code in "On Error Resume Next", then handle the error.
On Error Resume Next
Set field = custFields.Field("TEST", "TS_USER_88")
If Err.Number <> 0 Then
'Do Something to handle your error
'stuff
'Clear the error
Err.Clear
End If
On Error Goto 0
'more stuff down here
Here's some more info on the Err object and some of it's properties:
http://msdn.microsoft.com/en-us/library/sbf5ze0e(v=vs.84).aspx

Suppress popup window in vbs on timeout of Windows Update Search

I have a vb-script which checks if there are updates pending. Sometimes windows search returns an error (for example 503) and an error popup is generated. Since I'm not familiar with vbs, I don't know where to start searching for a solution.
Set updateSession = CreateObject("Microsoft.Update.Session")
Set updateSearcher = updateSession.CreateupdateSearcher()
Set searchResult = updateSearcher.Search("IsInstalled=0 and Type='Software'")
The problem occurs in line 3. It says:
Script: C:\path-to-my-script\my-script.vbs
Line: 3
Char: 1
Error: 0x80244022
Code: 80244022
Source: (null)
How can I either prevent the popup from being generated or get a handle to it and close it immediately?
Error 0x80244022 means that the update server HTTP service became temporarily unavailable (for whatever reason). See this MSKB article for a list of connectivity-related error codes.
To handle this error put it between an On Error Resume Next and an On Error Goto 0 statement:
Set updateSession = CreateObject("Microsoft.Update.Session")
Set updateSearcher = updateSession.CreateupdateSearcher()
On Error Resume Next
Set searchResult = updateSearcher.Search("IsInstalled=0 and Type='Software'")
If Err Then
'add logging routine here
WScript.Quit 1
End If
On Error Goto 0
'more code here
Note that the above will indiscriminately terminate the script on any error that occurs when calling the Search method. If you want to handle different errors in different ways, you could for instance put a Select statement inside the conditional:
If Err Then
Select Case Err.Number
Case &h80244022
'quit immediately
WScript.Quit 1
Case &h8009033F
'wait some time and retry
WScript.Sleep 900000
Set searchResult = updateSearcher.Search(...)
Case &h...
'just log a message and continue
...
End Select
End If

What does the "On Error Resume Next" statement do?

I came to some VBScript examples, and I saw the statement On Error Resume Next basically at the beginning of the script.
What does it do?
It basically tells the program when you encounter an error just continue at the next line.
It's worth noting that even when On Error Resume Next is in effect, the Err object is still populated when an error occurs, so you can still do C-style error handling.
On Error Resume Next
DangerousOperationThatCouldCauseErrors
If Err Then
WScript.StdErr.WriteLine "error " & Err.Number
WScript.Quit 1
End If
On Error GoTo 0
When an error occurs, the execution will continue on the next line without interrupting the script.
It means, when an error happens on the line, it is telling vbscript to continue execution without aborting the script. Sometimes, the On Error follows the Goto label to alter the flow of execution, something like this in a Sub code block, now you know why and how the usage of GOTO can result in spaghetti code:
Sub MySubRoutine()
On Error Goto ErrorHandler
REM VB code...
REM More VB Code...
Exit_MySubRoutine:
REM Disable the Error Handler!
On Error Goto 0
REM Leave....
Exit Sub
ErrorHandler:
REM Do something about the Error
Goto Exit_MySubRoutine
End Sub
It enables error handling. The following is partly from https://msdn.microsoft.com/en-us/library/5hsw66as.aspx
' Enable error handling. When a run-time error occurs, control goes to the statement
' immediately following the statement where the error occurred, and execution
' continues from that point.
On Error Resume Next
SomeCodeHere
If Err.Number = 0 Then
WScript.Echo "No Error in SomeCodeHere."
Else
WScript.Echo "Error in SomeCodeHere: " & Err.Number & ", " & Err.Source & ", " & Err.Description
' Clear the error or you'll see it again when you test Err.Number
Err.Clear
End If
SomeMoreCodeHere
If Err.Number <> 0 Then
WScript.Echo "Error in SomeMoreCodeHere:" & Err.Number & ", " & Err.Source & ", " & Err.Description
' Clear the error or you'll see it again when you test Err.Number
Err.Clear
End If
' Disables enabled error handler in the current procedure and resets it to Nothing.
On Error Goto 0
' There are also `On Error Goto -1`, which disables the enabled exception in the current
' procedure and resets it to Nothing, and `On Error Goto line`,
' which enables the error-handling routine that starts at the line specified in the
' required line argument. The line argument is any line label or line number. If a run-time
' error occurs, control branches to the specified line, making the error handler active.
' The specified line must be in the same procedure as the On Error statement,
' or a compile-time error will occur.
On Error Statement - Specifies that when a run-time error occurs, control goes to the statement immediately following the statement. How ever Err object got populated.(Err.Number, Err.Count etc)
On Error Resume Next means that On Error, It will resume to the next line to resume.
e.g. if you try the Try block, That will stop the script if a error occurred

Word macro error messages

I am changing document template macros. The one thing I can't find out how to do is to customize error messages. For example an error message in a document is
"Error! No table of figures entries found"
I would like to change this to display something else. Is it possible to do this with Word VBA or VBScript?
Is it possible to put this in some
kind of global error handler? – Craig
It is possible. Here is a very rough example.
In a standard module:
Sub HandleErr(ErrNo As Long)
Select Case ErrNo
Case vbObjectError + 1024
MsgBox "No table of figures entries found.", vbOKOnly + vbCritical
Case vbObjectError + 1034 To vbObjectError + 4999
MsgBox "Still no table of figures entries found.", vbOKOnly + vbCritical
Case Else
MsgBox "I give up.", vbOKOnly + vbCritical, _
"Application Error"
End Select
End Sub
Some code:
Sub ShowError()
Dim i As Integer
On Error GoTo Proc_Err
'VBA Error
i = "a"
'Custom error
If Dir("C:\Docs\TableFigs.txt") = "" Then
Err.Raise vbObjectError + 1024
End If
Exit_Here:
Exit Sub
Proc_Err:
If Err.Number > vbObjectError And Err.Number < vbObjectError + 9999 Then
HandleErr Err.Number
Else
MsgBox Err.Description
End If
End Sub
If you want to trap a specific error type in VBA, one method is to use On Error Resume Next then test for an error message on the line following the action to trap, e.g.:
On Error Resume Next
' try action
If Err.Number <> 0 Then
' handle w/ custom message
Err.Clear
End If
If you know the exact error number (If Err.Number = N Then), that would be better of course.
Well if you are talking about having a custom message box - that's easy.
Look up 'msgbox' in VBA help for better info.
Msgbox("Error! No table of figures entries found",16,"Error")
The 16 makes it a 'criticial' message.
If you're talking about error trapping then you'll need code like this:
On Error Resume Next
n = 1 / 0 ' this causes an error
If Err.Number <> 0 Then
n = 1
if Err.Number = 1 Then MsgBox Err.Description
End If
When an error is thrown, a number and description are given to the Err object.

Resources