1

如果发生错误,那么它将变为子 DisplayCustomError 但它不会引发异常。预期结果 - 在 objHTTP.send (json) 之后它应该抛出异常消息。我试过 Call Err.Raise 但它没有抛出任何东西。代码在VBscript中

 sub run
 On Error Resume Next
    wrapper.getVariable( "Plant_Price_PerKW" ).value = excel.range( "'Cases'!$H$331" )
    wrapper.getVariable( "Net_Present_Value" ).value = excel.range( "'Cases'!$H$782" )
    wrapper.getVariable( "IRR" ).value = excel.range( "'Cases'!$H$783" )
 Dim strMessage
    If Err.Number <> 0 And excel.range( "'Cases'!$H$783" ) = "" Then
     strMessage = "IRR cannot be computed. "
     DisplayCustomError(strMessage)
     WScript.Quit 
    ElseIf Err.Number <> 0 And (excel.range( "'Cases'!$H$783" ) <> "") Then
     strMessage = "Other Outputs cannot be computed."
     DisplayCustomError(strMessage)
     WScript.Quit 
    End If
end sub

Sub DisplayCustomError(strMessage)
If Err.Number <> 0 Then
    Dim errorMessage, objHTTP, URL, json, errorCode, uniqueId, networkInfo, jobId
    errorMessage ="Error while executing EVMLite. Error number " & Err.Number & ". " & Err.Description & " " & Err.Source & strMessage
    errorCode = "ERR-1004"
    uniqueId = wrapper.getVariable("UniqueId").value
    Set networkInfo = CreateObject("WScript.NetWork") 
    jobId = networkInfo.ComputerName
    Set objHTTP = CreateObject("MSXML2.ServerXMLHTTP")    
    URL = "http://10.93.244.224343:9005/vpp/logerror"
    objHTTP.Open "POST", URL, False
    objHTTP.SetRequestHeader "Content-Type", "application/json"
    json = "{""jobId"": """& jobId &""", ""uniqueId"": """& uniqueId &""", ""errorCode"": """& errorCode &""", ""errorMessage"": """& errorMessage &"""}"
    'MsgBox json
    objHTTP.send (json)

    On Error Goto 0

    Call Err.Raise(vbObjectError + 10, "EVM Failed to execute", errorMessage)
    'MsgBox objHTTP.ResponseText

 End If
end sub
4

1 回答 1

2

VBScript 实现的有趣之On Error处在于它不是全局的——它实际上受到范围的限制。因此,如果您On Error Resume Next在 Sub 或 Function 中应用,然后输入一个新的 Function 或 Sub 将其关闭,则该设置会在 Sub 或 Function 退出时恢复。

在您的情况下,您的Sub run集合On Error Resume Next,然后它调用Sub DisplayCustomErrorwhich sets On Error GoTo 0。这只适用于你还在里面的时候 DisplayCustomError。当它因 而退出时Err.Raise,您Sub run将继续,因为在该范围内,它仍设置为On Error Resume Next

On Error GoTo 0 Sub run调用之前,您需要明确说明DisplayCustomError

这是您可以测试的示例 VBS 文件。如果你运行它,不会抛出任何东西,程序将显示消息“完成”。如果取消注释 中的行Sub1,则会引发错误“示例 2”。

Sub Sub1()
    On Error Resume Next
    Err.Raise 1, "Example 1"
    'On Error Goto 0
    Sub2
End Sub

Sub Sub2()
    On Error Goto 0
    Err.Raise 2, "Example 2"
End Sub

Sub1
WScript.Echo "Done"
于 2017-08-04T12:47:25.617 回答