VBScript—エラー処理を使用する
-
03-07-2019 - |
質問
VBScriptを使用してエラーをキャッチしてログに記録し(エラー時に"何かを記録")、スクリプトの次の行を再開します。
たとえば、
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
&quot; On Error Goto [label]&quot;構文はVisual BasicおよびVisual Basic for Applications(VBA)でサポートされていますが、VBScriptはこの言語機能をサポートしていないため、上記のようにOn Error Resume Nextを使用する必要があります。
他のヒント
On Error Resume Next
はグローバルに設定されないことに注意してください。たとえば、コードの安全でない部分を関数に入れて、エラーが発生するとすぐに中断し、前の OERN
ステートメントを含むsubからこの関数を呼び出すことができます。
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
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()
はエラーを処理しないため(いいえ facade()
に On error resume next
) 、エラーは main()
に返され、 step4()
および step5()
は実行されません。
エラー処理は1コードブロックにリファクタリングされました