【问题标题】:Cloning VBScript Err Object克隆 VBScript Err 对象
【发布时间】:2012-11-04 14:35:32
【问题描述】:
下面的代码在尝试连接 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
是否可以克隆 err 对象?
【问题讨论】:
标签:
object
error-handling
vbscript
clone
【解决方案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
【解决方案2】:
要将全局 Err 对象的属性复制到新变量以供以后使用(在全局 Err 被新的灾难更改后。清除或“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 对象。