Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vbscript msxml12.XMLHTTP error handling

I use this vbscript code, to download web page:

Dim oXML
Set oXML = CreateObject("msxm12.XMLHTTP")
oXML.Open "GET", "mysite.com", False
oXML.Send

If there is no such web site, I get an error 80004005, Unspecified error at line "oXML.Open ..."

How can I handle this error in vbscript? I want to catch this error and show msgbox with my error, i.e. web page is not available.

like image 674
Michael Avatar asked Aug 15 '26 18:08

Michael


1 Answers

There are at least three possible points of failure in your script.

  1. CreateObject may fail; e.g. if you use msxml12 (digit 1) instead of msxml2 (letter l). Such blunders should be fixed during development.
  2. .Open may fail; e.g. if you use "mysite.com" instead of a syntactically correct URL. If you get the URL at runtime, a 'look before you jump' check is advisable, an OERN can be used to catch bad URLs not found by your validation.
  3. .Send may fail; e.g. if the site is down or abandoned. This is a clear case for an OERN.

The most important rule wrt OERN: Keep it local and short (Only one risky line between OERN and OEG0).

Demo code:

Option Explicit

Dim sUrl
For Each sUrl In Split("http://stackoverflow.com http://pipapo.org mysite.com")
    Dim oXML, aErr
'   Set oXML = CreateObject("msxm12.XMLHTTP")
    Set oXML = CreateObject("msxml2.XMLHTTP.6.0")
   On Error Resume Next
    oXML.Open "GET", sUrl, False
    aErr = Array(Err.Number, Err.Description)
   On Error GoTo 0
    If 0 = aErr(0) Then
      On Error Resume Next
       oXML.Send
       aErr = Array(Err.Number, Err.Description)
      On Error GoTo 0
       Select Case True
         Case 0 <> aErr(0)
           WScript.Echo "send failed:", aErr(0), aErr(1)
         Case 200 = oXML.status
           WScript.Echo sUrl, oXML.status, oXML.statusText
         Case Else
           WScript.Echo "further work needed:"
           WScript.Echo sUrl, oXML.status, oXML.statusText
       End Select
    Else
       WScript.Echo "open failed:", aErr(0), aErr(1)
    End If
Next

output:

cscript 24863986.vbs
http://stackoverflow.com 200 OK
send failed: -2146697211 The system cannot locate the resource specified.

open failed: -2147012890 System error: -2147012890.
like image 138
Ekkehard.Horner Avatar answered Aug 20 '26 05:08

Ekkehard.Horner