Creating a Generic Error Handler

One way of handling errors is to create a generic error handler that gets called from every sub procedure or function.

Try It Out Creating a Generic Error Handler

Create a generic error handler now.

1. Add the GeneralErrorHandler procedure that follows to the modBusinessLogic standard module.

Public Sub GeneralErrorHandler(lngErrNumber As Long, strErrDesc As String, strModuleSource As String, strProcedureSource As String)

Dim strMessage As String

'build the error message string from the parameters passed in strMessage = "An error has occurred in the application." strMessage = strMessage & vbCrLf & "Error Number: " & lngErrNumber strMessage = strMessage & vbCrLf & "Error Description: " & strErrDesc strMessage = strMessage & vbCrLf & "Module Source: " & strModuleSource strMessage = strMessage & vbCrLf & "Procedure Source: " & strProcedureSource

'display the message to the user MsgBox strMessage, vbCritical

End Sub

2. Add the procedure TestError2 to the modBusinessLogic standard module. Sub TestError2(intValue1 As Integer, intValue2 As Integer)

On Error GoTo HandleError

'declare variable to store result Dim intResult As Integer

'calculate result by dividing first value by second value intResult = intValue1 / intValue2

Exit Sub


GeneralErrorHandler Err.Number, Err.Description, "modBusinessLogic", _ "TestError2"

Exit Sub End Sub

3. Call the TestError2 procedure from the Immediate Window with the values shown in Figure 2.43.

Figure 2.43

4. The message box shown in Figure 2.44 is displayed.

0 0

Post a comment