如何忽略VBScript中的Internet错误?

时间:2017-09-28 10:43:42

标签: vbscript error-handling download

我有一个下载文件的vbscript。我需要这样做,以便如果没有互联网,它不会弹出错误消息The operation timed outFailed to find the resource specified。我已尝试使用On Error Resume Next,但唉它不会跳过任何与互联网相关的错误。我有什么方法可以设置超时或什么?它不是一个大文件,只是一个20行的文本文件。这是我的剧本:

strFileURL = "https://minecraft-statistic.net/en/server/167.114.43.185_25565/json/" 
strHDLocation = "c:\users\public\mc.txt"
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
  Set objFSO = Nothing
  objADOStream.SaveToFile strHDLocation
  objADOStream.Close
  Set objADOStream = Nothing
End if
Set objXMLHTTP = Nothing

1 个答案:

答案 0 :(得分:1)

On Error Resume Next是捕获错误的唯一选项,我不确定为什么你说它不起作用。这对我有用;

On Error Resume Next

strFileURL = "https://minecraft-statistic.net/en/server/167.114.43.185_25565/json/" 
strHDLocation = "c:\users\public\mc.txt"
Set objXMLHTTP = CreateObject("MSXML2.XMLHTTP")
objXMLHTTP.open "GET", strFileURL, false
objXMLHTTP.send()
If Err.Number = 0 Then
    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
        Set objFSO = Nothing
        objADOStream.SaveToFile strHDLocation
        objADOStream.Close
        Set objADOStream = Nothing
    End if
    Set objXMLHTTP = Nothing
Else
    'Handle the error here.
End If

On Error Resume Next的工作方式如下;

  1. Line触发由VBScript运行时捕获的错误。
  2. 错误记录在Err对象中。
  3. 跳过该行,然后运行下一个语句。
  4. 此过程将一直持续到达On Error Goto 0行,此时恢复默认行为。

    有用的链接