我想使用VBScript来捕获错误并记录它们(即出错“log something”)然后恢复脚本的下一行。

例如,

On Error Resume Next
'Do Step 1
'Do Step 2
'Do Step 3

当步骤1发生错误时,我希望它记录该错误(或用它执行其他自定义功能),然后在步骤2恢复。这可能吗?我该如何实现呢?

编辑:我可以这样做吗?

On Error Resume myErrCatch
'Do step 1
'Do step 2
'Do step 3

myErrCatch:
'log error
Resume Next
有帮助吗?

解决方案

VBScript没有抛出或捕获异常的概念,但运行时提供了一个全局Err对象,其中包含上次执行的操作的结果。您必须在每次操作后显式检查Err.Number属性是否为非零。

On Error Resume Next

DoStep1

If Err.Number <> 0 Then
  WScript.Echo "Error in DoStep1: " & Err.Description
  Err.Clear
End If

DoStep2

If Err.Number <> 0 Then
  WScript.Echo "Error in DoStop2:" & Err.Description
  Err.Clear
End If

'If you no longer want to continue following an error after that block's completed,
'call this.
On Error Goto 0

“On Error Goto [label]&quot; Visual Basic和Visual Basic for Applications(VBA)支持语法,但VBScript不支持此语言功能,因此您必须使用On Error Resume Next,如上所述。

其他提示

请注意, On Error Resume Next 未全局设置。您可以将不安全的代码部分放入函数中,如果发生错误,该函数会立即中断,并从包含先例 OERN 语句的子函数中调用此函数。

ErrCatch()

Sub ErrCatch()
    Dim Res, CurrentStep

    On Error Resume Next

    Res = UnSafeCode(20, CurrentStep)
    MsgBox "ErrStep " & CurrentStep & vbCrLf & Err.Description

End Sub

Function UnSafeCode(Arg, ErrStep)

    ErrStep = 1
    UnSafeCode = 1 / (Arg - 10)

    ErrStep = 2
    UnSafeCode = 1 / (Arg - 20)

    ErrStep = 3
    UnSafeCode = 1 / (Arg - 30)

    ErrStep = 0
End Function

我对VBScript非常陌生,所以这可能不被认为是最佳做法,或者可能有理由不应该这样做,我还没有意识到,但这是我提出的解决方案用来减少主代码块中错误记录代码的数量。

Dim oConn, connStr
Set oConn = Server.CreateObject("ADODB.Connection")
connStr = "Provider=SQLOLEDB;Server=XX;UID=XX;PWD=XX;Databse=XX"

ON ERROR RESUME NEXT

oConn.Open connStr
If err.Number <> 0 Then : showError() : End If


Sub ShowError()

    'You could write the error details to the console...
    errDetail = "<script>" & _
    "console.log('Description: " & err.Description & "');" & _
    "console.log('Error number: " & err.Number & "');" & _
    "console.log('Error source: " & err.Source & "');" & _
    "</script>"

    Response.Write(errDetail)       

    '...you could display the error info directly in the page...
    Response.Write("Error Description: " & err.Description)
    Response.Write("Error Source: " & err.Source)
    Response.Write("Error Number: " & err.Number)

    '...or you could execute additional code when an error is thrown...
    'Insert error handling code here

    err.clear
End Sub

您可以在外观函数中重新组合步骤函数调用:

sub facade()
    call step1()
    call step2()
    call step3()
    call step4()
    call step5()
end sub

然后,让你的错误处理在一个调用外观的上层函数中:

sub main()
    On error resume next

    call facade()

    If Err.Number <> 0 Then
        ' MsgBox or whatever. You may want to display or log your error there
        msgbox Err.Description
        Err.Clear
    End If

    On Error Goto 0
end sub

现在,让我们假设 step3()引发错误。由于 facade()不处理错误(没有 On error resume next facade()) ,错误将返回 main() step4() step5()将不会被执行。

您的错误处理现在在1个代码块中重构

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top