Creating Custom Assertions
This content is no longer actively maintained. It is provided as is, for anyone who may still be using these technologies, with no warranties or claims of accuracy with regard to the most recent product version or service release.
In some circumstances, you might not want to break into your code each time an assertion fails. For example, you might 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
See Also
Writing Error-Free Code | Design-Time Tools | Run-Time Tools | Script Debugging Tools | Understanding Conditional Compilation | Using Assertions | Handling Errors