Guy's Scripting Ezine 107 - Error Correcting Code
One of my best skills is anticipation, perhaps the result of playing chess in my youth. One of my worst skills is paying attention to
detail. Therefore, when it comes to troubleshooting VBScript, I have the skill to find the problems, but lack the desire to add error correcting code. I admit that I also shelter under the excuse
that error correcting code makes my example scripts too tortuous and therefore, more difficult to understand. This week I want to compensate for this omission and provide strategies for adding error
correcting code to your VBScripts.
This week's mission is to add error correcting code to your (or to my) scripts.
Let me ask this question: 'What happens to a script without extra code to trap errors?' The answer is nothing, provided the conditions are ideal. However, if there is an unexpected exception, then the script is likely to halt
with a WSH error box. For example, the script tries to
map a drive letter that is already in use.
To add comprehensive error correcting code takes at least twice the effort you invested in creating the original script. Therefore, in the case of 'run of the mill' scripts, I add error correcting techniques that are
merely 'good
enough'.
Back to anticipation. What I do is scan all the possible areas which could cause my lovely script to fail. Wrong syntax, faulty logic, uncontrolled exceptions e.g. null values, server not available.
Then if it's an important script, I go the extra mile and add error correcting code.
In the real world, you get
additional problems caused by psychotic users, who do things ordinary mortals could not imagine. Also, in some circumstances, there may be security concerns with hackers using your scripts for unintended
purposes.
To digress, where I come from in Wales, it's common to be referred to by your occupation, for example, Evans the Fish, or Jones the Coke (sold Coca Cola). In school my friend was always known as Davies Dead,
hid dad was an
undertaker.
Guy the Ruthless. (On Error Resume Next)
The first thing 'Guy the Ruthless' does is add Option Explicit at the beginning of each VBScript. This forces me to declare all variables, and thus avoid careless errors. For example, if I begin by
calling a variable objNetwork, but then refer to it as strNetwork, Option Explicit warns me that I have not declared strNetwork. Thus preventing me making a logical error later in the script.
If I still find my script gives a problem, then I crudely and ruthlessly, add On Error Resume Next. When you employ On Error Resume Next, it is best is to add this command to the line immediately before the
error.
By the way, even 'Guy the Ruthless' tests the script, this throws up any silly syntax errors. What transforms 'Guy the Ruthless' from an average scriptwriter to a good script writer, is a top-notch script editor.
Investigate a
program such as OnScript which identifies the line numbers and color codes objects, methods and string variables. Get your evaluation copy of OnScript
Guy the Conscientious
The first thing 'Guy the Conscientious' does is remind himself of Murphy's Law; what can go wrong will go wrong. This jolts me into anticipation mode where I ask myself, 'what if'. What if the drive
letter is already in use? What if there is no value in the spreadsheet's cell.
Guy the Conscientious extends testing; he deliberately makes the script fail, for instance, by trying to map a drive to a letter he knows is already in use. He then records the error message and writes code to 'handle' the
halted script.
The technique involves a special VBScript object called 'err'. Err has a property called number, therefore the first stage when looking for clues is to add this line: WScript.echo "Error code
is " & err.number.
We hope that the result will be zero, meaning no error. However, we must prepare for the worst, if the 'device is already in use, then you get an err.number such as -2147024811. The key connection is
realizing that this pure decimal number has a
hex equivalent of 80070055. The eureka moment come when you realize that this is the very same number which is displayed in the WSH error message box. You can induce the error by deliberately
running the script for a second time (Remove On error resume next).
If you want to test at home launch the scientific calculator, click the decimal button and paste: -2147024811, next, click the hex button on the scientific calculator, expected result (FFFFFFFF) 80070055.
Guy the Conscientious makes a special study of these hex numbers, which begin with 800x0000. If you analyse the hex error message, you get a valuable clue depending on whether x (fourth digit) = 4,5, 7 or A.
For example, 5 = ADSI, 7 = logical, A= Syntax. Therefore the 8007xxxx series are logical errors such as drive in use or server not available; they are not the fault of VBScript errors.
Guy the Logical
If you take error correcting code to the highest level, you need to combine knowledge of the hex and decimal codes with If ...then.. else... End If logic. In other words, so you have a problem - what are
you going to about it? For example, if the drive is already connected, then you could run a sub-routine to disconnect it. I have to say that if you go this extra mile and error correcting code, you
always get that feeling of satisfaction.
Sometimes you get lucky and VBScript has an 'If Exist' command, for example, with File Scripting Object: If objFSO.FolderExists(strDirectory). Unfortunately, MapNetworkDrive does not have an If Exist
construction, therefore we are going to learn error correcting code from the bottom up. This week I am going to show you how to analyze the err.numbers. Next week we concentrate on putting the logic into
practice.
If you are looking for handy network utilities, try some of the free downloads at
Tools4Ever
This week, I want I want to build up gradually. Therefore we start with a script which just map's the drive. Later, in Example 2, I will modify the script to echo the problem. Then in Example
3, I am going to develop error correcting logic and also indulge my passion for Select Case, rather than use a succession of 'if else'
statements.
Pre-requisites You need a free local drive letter. Rather eccentrically, I have chosen letter U as the drive letter because my H: is already in use. Feel free to amend strDriveLetter. You will need a
shared folder. If no other machine is available, share out a folder on your own machine. Make sure that you amend strRemotePath to reflect your UNC path and not mine. This script should work
on any Windows, machine.
Instructions for mapping a network drive (Preparation Script) Copy and paste the example script below
into notepad or use a VBScript editor.
One advantage of a good script editor such as OnScript is that it displays a methods arguments.Get your evaluation copy of OnScript
Save the file with a .vbs extension, for example: BasicOnErr.vbs
Double click BasicOnErr.vbs, the check the drive letters with Windows Explorer, note any WSH 800x0000 error messages.
' BasicOnErr.vbs ' VBScript to demonstrate error correcting code ' Authors Guy Thomas ' Version 1.4 - March 2006 ' ------------------------------------------------' '
Option Explicit Dim objNetwork, strDrive, objShell Dim strRemotePath, strDriveLetter ' strDriveLetter = "u:" strRemotePath = "\\grand\ezine"
On Error Resume Next
Set objNetwork =
CreateObject("WScript.Network") objNetwork.MapNetworkDrive strDriveLetter, strRemotePath
WScript.Quit
' End of script.
Learning Points
Note 1: Get into the habit of using Option Explicit at the start of your scripts. What Option Explicit does is force you to declare all your variables before you use them. The benefit
is it saves typos in variable names.
Note 2: The only real error correcting code is the crude, but effective, On Error Resume Next. What this does is permit the script to continue instead of halting with a WSH error message box.
Naturally it does not so much cure the problem, as sweep it under the carpet.
Note 3: Not demonstrated here, but if you wished to reverse On Error Resume Next, add 'On Error GoTo 0'. N.B. Type: GoTo not Go To, and that's a zero not an oh.
Here is a script which is designed for research. This is the middle stage in developing error correcting code. The technique is to do things that
deliberately make the script go wrong. For example, change the server name and thus induce an error by making the code try to map a non-existent UNC path.
' ErrorCorrecting.vbs ' VBScript to demonstrate error correcting code ' Authors Guy Thomas ' Version 2.4 - March 2006 ' ------------------------------------------------'
' Option Explicit Dim objNetwork, strDrive, objShell Dim strRemotePath, strDriveLetter ' strDriveLetter = "u:" strRemotePath = "\\grand\ezine" err.Clear
On Error Resume Next
Set objNetwork = CreateObject("WScript.Network") objNetwork.MapNetworkDrive strDriveLetter, strRemotePath
if err.number <> 0 then WScript.Echo "Error number " & err.number
WScript.Quit(0)
' End of script.
Learning Points
Note 1: The whole point of this script is to introduce my favourite troubleshooting technique, adding WScript.Echo at key points in a fault script. Here we echo the err.number. Once we have one, or preferably more err.numbers then we
progress to Example 3. Hidden away on line 27, Err.Number is the star command of this script. What it does is expose the reason the script failed. In fact, err.number is only the first part
of the error correcting processes. In a real life script you would then make the instructions fork and take corrective action. For example, if the drive letter was already in use (-2147024811) then you could run a sub
routine to disconnect the mapped network drive. Such a sub-routine is not included in this script as we are building up gradually. Next week will explore taking logical action based on error, but
this week I want to concentrate on researching with err.number. Instructions Here is a golden opportunity to make the script go wrong by deliberately trying to map to a non existent UNC path,
or to drive letters that are already in use.
' ErrorCorrecting.vbs ' VBScript to demonstrate error correcting code ' Authors Guy Thomas ' Version 2.3 - March 2006 ' ------------------------------------------------'
' Option Explicit Dim objNetwork, strDrive, objShell Dim strRemotePath, strDriveLetter ' strDriveLetter = "u:" strRemotePath = "\\grand\ezine" err.Clear
On Error Resume Next
Set objNetwork = CreateObject("WScript.Network") objNetwork.MapNetworkDrive strDriveLetter, strRemotePath
if err.number <> 0 then call ECCode ' Clear error else error number carries over and
script fails Err.clear
WScript.Quit(0)
sub ECCode() Select Case err.number Case -2147024811 WScript.Echo "Drive in use" Case -2147023693 WScript.Echo "No Server" Case -2147942453
WScript.Echo "Network PATH not found" Case -2147942467 WScript.Echo "Network NAME not found" Case 0 WScript.Echo " ok" Case else Wscript.Echo "Investigate " & err.number End Select
WScript.Quit(1) End Sub
' End of script.
Learning Points
Note 0: When you use a script editor such as OnScript, it helps you by displaying line numbers and color coded commands. Get your evaluation copy of OnScript
Note 1: Investigate sub ECCode. Understand how Select Case replaces multiple If then.... ElseIf statements. Check the rhythm of each line, Case number (or condition), action.
Note 2: Trace where the main script calls the sub routine. Pay attention to where you need brackets; yes when you define sub ECCode(), no where you simply call ECCode.
Challenges
My challenge is open ended. Decide what level of error correcting code your scripts need. Experiment, then test, various logic routines to handle unexpected situations.
This week I wanted to concentrate on error correcting strategies. Tactics such as 'Option Explicit' and 'On Error Resume next', are easy to understand and implement. However, adding true error correcting
code based on err.number is time consuming. The final piece in the error correcting jigsaw is logic.
Next week I will develop the error logic so that it actually takes corrective action and thus handle errors usefully and gracefully.
Their topics and material are ideal for getting you started with VBScript. The
videos are easy to follow and you can control the pace. Try their free demo material and then see if you want to buy the full package.
See more about VB Script Training CD.
|