克隆VBScript Err对象

时间:2012-11-04 14:35:32

标签: object error-handling vbscript clone

以下代码在尝试连接echo中的error.no时出现错误Variable is undefined (500)

'Raise an error to represent an issue with the main code
err.raise 999

dim error
set error = err

'Call another function that could also throw an error
SendMail "To=me","From=me","Subject=Failure in main code"

'Report both errors
wscript.echo "First problem was - Error code:" & error & vbcrlf & "Subsequent problem was - Error code:" & err

是否可以克隆错误的对象?

2 个答案:

答案 0 :(得分:1)

除了Ekkehard.Horner之外,您还可以创建一个与错误对象具有相同行为的自定义错误类。因为err对象是全局的,所以可以在类中加载它而不将其传递给方法。

On error resume Next
a = 1 / 0
Set myErr = new ErrClone
On error goto 0

WScript.Echo myErr  
' returns 11, the default property
WScript.Echo myErr.Number & vbTab & myErr.Description & vbTab & myErr.Source
' returns 11      Division by zero      Microsoft VBScript runtime error

Class ErrClone

    private description_, number_, source_

    Public Sub Class_Initialize
        description_ = Err.Description
        number_ = Err.Number
        source_ = Err.Source
    End Sub

    Public Property Get Description
        Description = description_
    End Property
    Public Default Property Get Number
        Number = number_
    End Property
    Public Property Get Source
        Source = source_
    End Property
End Class

答案 1 :(得分:0)

要将全局Err对象的属性复制到新变量以供以后使用(在全局Err被新灾难更改.Clear或“On Error GoTo 0”之后),您应该使用数组:

>> On Error Resume Next
>> a = 1 / 0
>> Dim aErr : aErr = Array(Err.Number, Err.Description, Err.Source)
>> On Error GoTo 0
>> WScript.Echo Join(aErr, "-")
>>
11-Division by zero-Microsoft VBScript runtime error

因为你无法在VBScript中创建一个空的Err对象。