Sunday, October 30, 2011

Error Handling: An Example

Consider the following standard WMI query for a moment. Look at the code for a few seconds, at least...

[CODE]
strComputer = "computer123"
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2") Set colItems = objWMIService.ExecQuery("Select * from Win32_PhysicalMemory",,48)
For Each objItem in colItems Wscript.Echo "Caption: " & objItem.Caption 
Next
[/CODE]

What could go wrong? What if "Computer123" doesn't exist?  What if "Computer123" is offline, or the firewall prevents a connection?  What if your user account doesn't have permissions to query remote WMI?  What if you typed in the wrong WMI class name, like "Win32_RAM" or something else?

You might get something like this...


[OUTPUT]
C:\Scripts\wmi-test.vbs(3, 1) Microsoft VBScript runtime error: _
The remote server machine does not exist or is unavailable: 'GetObject'
[/OUTPUT]
Is that a good way to handle this failure?  What if we add some explicit error checking and then handle the error?  Let's try this...


[CODE]
strComputer = "computer123" On Error Resume Next
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2") If err.Number <> 0 Then
wscript.echo "unable to connect to: " & strComputer
wscript.echo "error: " & err.Number & " / " & err.Description
wscript.quit(err.Number)
End If
Set colItems = objWMIService.ExecQuery("Select * from Win32_PhysicalMemory",,48)
For Each objItem in colItems Wscript.Echo "Caption: " & objItem.Caption 
Next
[/CODE]


Now, if we run this and "Computer123" is not accessible, we should get the following...



[OUTPUT]
unable to connect to: computer123
error: 462 / The remote server machine does not exist or is unavailable

[/OUTPUT]


If we check %errorlevel% is should be set to 462 now as well.  This is an example of raising an error "implicitly" or simply passing it up without modifying it.  If we want to force our own error result value, we can simply modify the wscript.quit(value) statement to use our own numeric value...



[CODE]
strComputer = "computer123" On Error Resume Next
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2") If err.Number <> 0 Then
wscript.echo "unable to connect to: " & strComputer
wscript.echo "error: " & err.Number & " / " & err.Description
wscript.quit(5)
End If
Set colItems = objWMIService.ExecQuery("Select * from Win32_PhysicalMemory",,48)
For Each objItem in colItems Wscript.Echo "Caption: " & objItem.Caption 
Next
[/CODE]


Now, the exit code (or %errorlevel%) value will be 5 when it fails for *ANY* reason.  There are situations when you will want to force a static error result, and situations where you want the real error value.  It's nice to know you have that option, and YOU have control over it.

Enjoy!

No comments: