Microsoft Office 2000/Visual Basic Programmer's Guide |
In some circumstances you may not want to break into your code each time an assertion fails. For example, you may want to log assertion information to a file and use an error handler to handle any errors that result from the bad data. With a little bit of planning, you can create code to use while debugging that will let you handle assertions according to a flag you pass to a general routine. For example, the following procedure accepts arguments representing an assertion expression to test, the text of the assertion expression, the calling procedure's name, and a flag indicating how to display or log a failed assertion:
Function CustomAssertError(varExpression As Variant, _
strExpression As String, _
strCallingProc As String, _
Optional intOutputType As Integer = 0) As Boolean
Dim intFileNum As Integer
Dim strErrorMessage As String
Const DEBUG_LOGFILE As String = "c:\CustomAssertLog.txt"
#If FLAG_DEBUG = True Then
If varExpression = False Then
strErrorMessage = "ASSERTION FAILURE! " & Now() & vbCrLf _
& "The expression: " & vbCrLf & "'" & strExpression & "'" _
& vbCrLf & "Called from: " & vbCrLf & "'" & strCallingProc _
& "'" & vbCrLf & "failed!"
Select Case intOutputType
Case 0
' Display in message box.
MsgBox strErrorMessage
Case 1
' Write to Debug window.
Debug.Print strErrorMessage
Case 2
' Write to text file on disk.
intFileNum = FreeFile
Open DEBUG_LOGFILE For Append As #intFileNum
Write #intFileNum, strErrorMessage
Close #intFileNum
Case Else
Stop
End Select
End If
#End If
End Function
To experiment with the different ways to call the CustomAssertError procedure, examine the TestCustomAssertError procedure; both of these procedures are available in the modErrorCode module in ErrorHandlers.dot in the ODETools\V9\Samples\OPG\Samples\CH08 subfolder on the Office 2000 Developer CD-ROM.