-
Notifications
You must be signed in to change notification settings - Fork 45
Error management in VBAToolKit
While coding VBAToolKit, we thought it could be nice if errors could work their way up the stack, instead of popping a MsgBox with a low-level error message that users won't understand.
To implement this, we considered the fact that in a called function, an error raised in the error handler is actually passed to the caller function.
For example, the following code :
Public Sub caller()
On Error GoTo callerErr
called
callerErr:
MsgBox "Error " & err.Number & " in " & err.Source & " : " & err.Description
End Sub
Public Sub called()
On Error GoTo calledErr
err.Raise 3600,"Sub 'called'", "dummy error"
calledcalledErr:
err.Raise err.Number, err.Source, err.Description
Exit Sub
End Sub
will pop a MsgBox displaying "Error 3600 in 'Sub called' : dummy error"
when running caller
.
It can work with every number of levels.
This example with 3 levels will pop the very same MsgBox :
Public Sub caller()
On Error GoTo callerErr
called
callerErr:
MsgBox "Error " & err.Number & " in " & err.Source & " : " & err.Description
End Sub
Public Sub called()
On Error GoTo calledErr
calledcalled
calledErr:
err.Raise err.Number, err.Source, err.Description
Exit Sub
End Sub
Public Sub calledcalled
On Error GoTo calledcalledErr
err.Raise 3600,"Sub 'calledcalled'", "dummy error"
calledcalledErr:
err.Raise err.Number, err.Source, err.Description
Exit Sub
End Sub
This allows the filtering of errors rising from the depths of the code to produce custom errors messages relevant to the user.
For example, the code :
Public Sub caller()
On Error GoTo callerErr
called
callerErr:
MsgBox "Error " & err.Number & " in " & err.Source & " : " & err.Description
End Sub
Public Sub called()
On Error GoTo calledErr
calledcalled
calledErr:
err.Raise 6666, "Sub 'called'", "Something went wrong."
Exit Sub
End Sub
Public Sub calledcalled
On Error GoTo calledcalledErr
err.Raise 3600,"'Sub calledcalled'", "Cryptic error message"
calledcalledErr:
err.Raise err.Number, err.Source, err.Description
Exit Sub
End Sub
will display to the user "Error 6666 in 'Sub called' : Something went wrong."
.
Please note that this mechanism has not yet been implemented in the entire project.