I'm not sure, what you want to do:
1) If you want to set an errorlevel if objXMLHTTP.Status is not 200, then just add these lines prior to End if:
2) If you want to set the errorlevel to 1 if a file is created (else it is 0 even on errors), just add this to the end (assumed that this file doesn't exist on start):
Code: Select all
Set objFileSystem = CreateObject("Scripting.FileSystemObject")
If objFileSystem.FileExists(strHDLocation) Then
WScript.Quit(1)
End If
3) If you want to do some simple error checking within the script, you may do something like this:
Code: Select all
Option Explicit
On Error resume next
Err.Clear
Dim objString : objString = "MSXML200000.XMLHTTP"
Set objXMLHTTP = CreateObject(objString)
If Err.Number <> 0 Then
WScript.Echo("Error: Could not create object: '" & objString & "'.")
WScript.Quit(1)
End If
On Error goto 0
4) If you want to do excessive error checking within the script, you may do something like this:
Code: Select all
Option Explicit
Class Inet
Dim objXMLHTTP
Dim objADOStream
Dim objFSO
Dim Called
Function Download (strFileURL, strHDLocation)
Called = 0
Download = 0
Set objXMLHTTP = CreateObject("MSXML2.XMLHTTP")
objXMLHTTP.open "GET", strFileURL, false
objXMLHTTP.send()
If objXMLHTTP.Status = 200 Then
Set objADOStream = CreateObject("ADODB.Stream")
objADOStream.Open
objADOStream.Type = 1 'adTypeBinary
objADOStream.Write objXMLHTTP.ResponseBody
objADOStream.Position = 0 'Set the stream position to the start
Set objFSO = Createobject("Scripting.FileSystemObject")
If objFSO.Fileexists(strHDLocation) Then objFSO.DeleteFile strHDLocation
objADOStream.SaveToFile strHDLocation
objADOStream.Close
Set objADOStream = Nothing
If objFSO.Fileexists(strHDLocation) Then Download = 1
Set objFSO = Nothing
End if
Set objXMLHTTP = Nothing
End Function
Private Sub CatchErr_Download
Select Case Err.Number
Case 0
Case 429
Dim obj : obj = Mid(Err.Description, InStr (Err.Description, "'") + 1, Len(Err.Description) - InStr (Err.Description, "'") - 1)
If StrComp(obj,"ADODB.Stream") Then
Set objXMLHTTP = Nothing
ElseIf StrComp(obj,"Scripting.FileSystemObject") Then
On Error Resume Next
objADOStream.Close
On Error goto 0
Set objADOStream = Nothing
Set objXMLHTTP = Nothing
Else
WScript.Echo "No exception handling on failed creation of the activeX object: '" & obj & "'."
End If
Case Else WScript.Echo "Unhandled error (" & Err.Number & ", " & Err.Source & "," & Err.Description & ") occurred."
End Select
Err.Clear
End Sub
Private Sub Class_Terminate
Select Case Err.Number
Case 0 CatchErr_Download
Case Else WScript.Echo "Unknown function called."
End Select
End Sub
End Class
Dim objInet : Set objInet = New Inet
Select Case objInet.Download("http://example.com/data/file.ext", "C:\Temp\batch\test\file.ext")
Case 1
WScript.Echo "File downloaded."
Case Else
WScript.Echo "No File downloaded."
End Select
Set objInet = Nothing
This is an exemplary error handling of two errors, not of all.
penpen