2017-08-04 50 views
1

如果發生錯誤,那麼它將分DisplayCustomError,但它不會拋出異常。 預期結果 - 在objHTTP.send(json)之後,它應該拋出異常消息。我曾嘗試調用Err.Raise,但它不會拋出任何東西。該代碼是用VBScriptVBScript上的錯誤處理:不拋出錯誤

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 
+0

您正在使用'On Error Resume Next',它會忽略錯誤。刪除。 – braX

+0

@braX我試圖刪除On Error Resume NextSub,它拋出的異常,但它不會進入子DisplayCustomError(strMessage),當我第二次運行時,它將分DisplayCustomError(strMessage) –

+0

找到一種方法來測試條件導致你正在得到的任何錯誤,然後使用if語句來避免發生錯誤。根據發生的錯誤,編寫代碼是一種不好的方法。 – braX

回答

2

有關VBScript的執行On Error有趣的是,它不是全局的 - 它實際上是由範圍的限制。因此,如果您在Sub或Function中應用On Error Resume Next,然後輸入一個新的將其關閉的Function或Sub,則當該Sub或Function退出時,該設置將恢復。

在你的情況下,你的Sub run設置On Error Resume Next,然後它調用Sub DisplayCustomError其中設置On Error GoTo 0。這僅適用於,而您仍在DisplayCustomError之內。當它由於Err.Raise而退出時,您的Sub run將繼續執行,因爲在該範圍內,它仍然設置爲On Error Resume Next

您撥打電話到DisplayCustomError

之前,您需要明確說明On Error GoTo 0Sub run這裏的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" 
+0

我已經把錯誤轉到0並且在DisplayCustomError(strMessage)之前調用Err.Raise並且移除了WScript.Quit。現在它正在工作,它正在拋出我想要的錯誤。謝謝你的幫助。欣賞它。 –

+0

@DevendraVastrakar非常歡迎您!不要忘記通過點擊投票按鈕下面的勾號來接受這個答案。 :) – BoffinbraiN