what is the better way to handle errors in VB6

前端 未结 7 705
再見小時候
再見小時候 2020-11-30 06:43

I have VB6 application , I want to put some good error handling finction in it which can tell me what was the error and exact place when it happened , can anyone suggest th

7条回答
  •  -上瘾入骨i
    2020-11-30 07:17

    I use a home-grown Error.bas module to make reporting and re-raising less cumbersome.

    Here's its contents (edited for length):

    Option Explicit
    
    Public Sub ReportFrom(Source As Variant, Optional Procedure As String)
        If Err.Number Then
            'Backup Error Contents'
            Dim ErrNumber As Long: ErrNumber = Err.Number
            Dim ErrSource As String: ErrSource = Err.Source
            Dim ErrDescription As String: ErrDescription = Err.Description
            Dim ErrHelpFile As String: ErrHelpFile = Err.HelpFile
            Dim ErrHelpContext As Long: ErrHelpContext = Err.HelpContext
            Dim ErrLastDllError As Long: ErrLastDllError = Err.LastDllError
        On Error Resume Next
            'Retrieve Source Name'
            Dim SourceName As String
            If VarType(Source) = vbObject Then
                SourceName = TypeName(Source)
            Else
                SourceName = CStr(Source)
            End If
            If LenB(Procedure) Then
                SourceName = SourceName & "." & Procedure
            End If
            Err.Clear
            'Do your normal error reporting including logging, etc'
            MsgBox "Error " & CStr(ErrNumber) & vbLf & "Source: " & ErrSource & vbCrLf & "Procedure: " & SourceName & vbLf & "Description: " & ErrDescription & vbLf & "Last DLL Error: " & Hex$(ErrLastDllError)
            'Report failure in logging'
            If Err.Number Then
                MsgBox "Additionally, the error failed to be logged properly"
                Err.Clear
            End If
        End If
    End Sub
    
    Public Sub Reraise(Optional ByVal NewSource As String)
        If LenB(NewSource) Then
            NewSource = NewSource & " -> " & Err.Source
        Else
            NewSource = Err.Source
        End If
        Err.Raise Err.Number, NewSource, Err.Description, Err.HelpFile, Err.HelpContext
    End Sub
    

    Reporting an error is as simple as:

    Public Sub Form_Load()
    On Error Goto HError
        MsgBox 1/0
        Exit Sub
    HError:
        Error.ReportFrom Me, "Form_Load"
    End Sub
    

    Reraising an error is as simple as calling Error.Reraise with the new source.

    Although it is possible to retrieve the Source and Procedure parameters from the call stack if you compile with symbolic debug info, it's not reliable enough to use in production applications

提交回复
热议问题