Search code examples
objecterror-handlingvbscriptclone

Cloning VBScript Err Object


The below code gives the error Variable is undefined (500) when trying to concatenate the error.no in the echo:

'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

Is it possible to clone the err object?


Solution

  • In addition to Ekkehard.Horner, you can also create a custom error class with the same behaviour as the error object. Because the err object is global, you can load it inside the class without passing it to it in a method.

    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