Check if object exists in VBScript - 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

Related

Handling VBScript errors when calling script using 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

Vbscript type mismatch error apparently not justifiable

I'm trying to figure out why I would get this error for the code below. I've searched on the web for possible causes but I couldn't find. Please have a look:
Dim descr, code
If WScript.Arguments.Count = 0 Then
Set objShell = CreateObject("Shell.Application")
objShell.ShellExecute "wscript.exe", Chr(34) & Script.ScriptFullName Chr(34) & " Run", , "runas", 1
Else
descr = InputBox("restore point description","Crepo")
If (descr) Then
code = GetObject("winmgmts:\\.root default:Systemrestore").CreateRestorePoint (descr, 0, 100)
If (code) Then
Msgbox "System Restore Point not created (" & code & ") !", 48, "Crepo"
Else
Msgbox "System Restore Point successfully created", 64, "Crepo"
End If
End If
End If
At runtime, if I input anything, i.e. qwerty I get this error:
Line: 8
Char: 2
Error: Type mismatch: '[string: "qwerty"]'
Code: 800A000D
From my researches, return type of InputBox is string and CreateRestorePoint first argument is also string. In fact, it works if I call InputBox directly as the argument.
The If clause needs a boolean (not a string):
>> descr = "qwerty"
>> If (descr) Then WScript.Echo "nonsense"
>>
Error Number: 13
Error Description: Type mismatch
InputBox returns a string or an empty value (see here), but never Null.
Instead of If (descr) Then try If (Not IsNull(descr)) Then.
You may also want to check for empty strings too: If (Not IsNull(descr) and descr <> "") Then. In fact, as pointed out in the other answer, since the VBScript InputBox function docs note that If the user clicks Cancel, the function returns a zero-length string ("") you definitely need to check for an empty/zero-length string.

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

VB6 - How to catch exception or error during runtime

I developed an application in VB6. In client's environment it raises runtime errors which I can't reproduce under debugger. Is there any way to get the stacktrace or location of error?
I created log file and
I used
Err.Description,Err.Source
but it gives blank values.
Please help me.
my method(......
On Error GoTo Error_Handler
.........
Error_Handler :
writeToLogFile(Err.Source,Err.Description)
You've probably done something to clear the Err object before writing to the log file. This is very, very easy to do. What you'll want to do is as soon as you detect an error has occurred, grab the error message before doing anything else. Then pass the error message to whatever logging routine you're using. E.g.:
Dim sMsg As String
On Error Goto ErrHandler
' ...code here...
Exit Function
ErrHandler:
sMsg = "Error #" & Err.Number & ": '" & Err.Description & "' from '" & Err.Source & "'"
GoLogTheError sMsg
BTW, thanks for your guys' answers helping me. I'm about half a decade late to the game of VB6. I don't do windows unless forced to. ;)
Anyhow, when doing your error checking, say among 3000 individual record query insertions, I learned a couple tricks. Consider this block of code:
'----- order number 1246-------
On Error Goto EH1246:
sSql="insert into SalesReceiptLine ( CustomerRefListID,TemplateRe..."
oConnection.Execute sSQL
sSql="SELECT TxnID FROM SalesReceiptLine WHERE RefNumber='1246'..."
oRecordset.Open sSQL, oConnection
sTxnId = oRecordset(0)
oRecordset.Close
sSql="INSERT INTO SalesReceiptLine (TxnId,SalesReceiptLineDesc,Sal..."
oConnection.Execute sSQL
EH1246:
IF Err.Number<>0 THEN
sMsg = sMsg & "Order # 1246; sTxnId = " & sTxnId & _
vbCrLf & Err.Number & ": " & Err.Description & vbCrLf
sErrOrders = sErrOrders & "1246,"
End If
On Error GoTo -1
'----- order number 1247-------
On Error Goto EH1247:
When not testing for Err.Number, you'll get a 0: on every order handled. (maybe you don't want that). The On Error GoTo -1 resets the error so that it will work again. Apparently, Err only works "once".
I wrote a php script to build the VB6 source code to run some 8000 odbc queries... :P
Do you definitely, positively have an Exit Function just above the Error_Handler:?
my method(......
On Error GoTo Error_Handler
........
Exit Sub
Error_Handler :
writeToLogFile(Err.Source,Err.Description)
"Exit Sub" should be added before you handle the Error_Handler function.....

what is the better way to handle errors in VB6

I have VB6 application , I want to put some good error handling finction in it which can tell me what was the error and exact place when it happened , can anyone suggest the good way to do this
First of all, go get MZTools for Visual Basic 6, its free and invaluable. Second add a custom error handler on every function (yes, every function). The error handler we use looks something like this:
On Error GoTo {PROCEDURE_NAME}_Error
{PROCEDURE_BODY}
On Error GoTo 0
Exit {PROCEDURE_TYPE}
{PROCEDURE_NAME}_Error:
LogError "Error " & Err.Number & " (" & Err.Description & ") in line " & Erl & _
", in procedure {PROCEDURE_NAME} of {MODULE_TYPE} {MODULE_NAME}"
Then create a LogError function that logs the error to disc. Next, before you release code add Line Numbers to every function (this is also built into MZTools). From now on you will know from the Error Logs everything that happens. If possible, also, upload the error logs and actually examine them live from the field.
This is about the best you can do for unexpected global error handling in VB6 (one of its many defects), and really this should only be used to find unexpected errors. If you know that if there is the possibility of an error occurring in a certain situation, you should catch that particular error and handle for it. If you know that an error occurring in a certain section is going to cause instability (File IO, Memory Issues, etc) warn the user and know that you are in an "unknown state" and that "bad things" are probably going happen. Obviously use friendly terms to keep the user informed, but not frightened.
a simple way without additional modules, useful for class modules:
pre-empt each function/subs:
On Error Goto Handler
handler/bubbleup:
Handler:
Err.Raise Err.Number, "(function_name)->" & Err.source, Err.Description
voila, ghetto stack trace.
I use a home-grown Error.bas module to make reporting and re-raising less cumbersome.
Here's its contents (edited for length):
Option Explicit
Public Sub ReportFrom(Source As Variant, Optional Procedure As String)
If Err.Number Then
'Backup Error Contents'
Dim ErrNumber As Long: ErrNumber = Err.Number
Dim ErrSource As String: ErrSource = Err.Source
Dim ErrDescription As String: ErrDescription = Err.Description
Dim ErrHelpFile As String: ErrHelpFile = Err.HelpFile
Dim ErrHelpContext As Long: ErrHelpContext = Err.HelpContext
Dim ErrLastDllError As Long: ErrLastDllError = Err.LastDllError
On Error Resume Next
'Retrieve Source Name'
Dim SourceName As String
If VarType(Source) = vbObject Then
SourceName = TypeName(Source)
Else
SourceName = CStr(Source)
End If
If LenB(Procedure) Then
SourceName = SourceName & "." & Procedure
End If
Err.Clear
'Do your normal error reporting including logging, etc'
MsgBox "Error " & CStr(ErrNumber) & vbLf & "Source: " & ErrSource & vbCrLf & "Procedure: " & SourceName & vbLf & "Description: " & ErrDescription & vbLf & "Last DLL Error: " & Hex$(ErrLastDllError)
'Report failure in logging'
If Err.Number Then
MsgBox "Additionally, the error failed to be logged properly"
Err.Clear
End If
End If
End Sub
Public Sub Reraise(Optional ByVal NewSource As String)
If LenB(NewSource) Then
NewSource = NewSource & " -> " & Err.Source
Else
NewSource = Err.Source
End If
Err.Raise Err.Number, NewSource, Err.Description, Err.HelpFile, Err.HelpContext
End Sub
Reporting an error is as simple as:
Public Sub Form_Load()
On Error Goto HError
MsgBox 1/0
Exit Sub
HError:
Error.ReportFrom Me, "Form_Load"
End Sub
Reraising an error is as simple as calling Error.Reraise with the new source.
Although it is possible to retrieve the Source and Procedure parameters from the call stack if you compile with symbolic debug info, it's not reliable enough to use in production applications
ON ERROR GOTO
and the
Err
object.
There is a tutorial here.
Yes, take Kris's advice and get MZTools.
You can add line numbers to section off areas of complex procedures, which ERL will report in the error handler, to track down which area is causing the error.
10
...group of statements
20
...group of statements
30
...and so on
Use on
dim errhndl as string
on error goto errhndl
errhndl:
msgbox "Error"
Use the On Error statement and the Err object.

Resources