Pattern to handle expected errors locally, rethrow unexpected errors

后端 未结 4 907
再見小時候
再見小時候 2021-02-13 22:16

Sometimes a certain bit of code will raise an error in an expected way, and it\'s most convenient to handle it locally rather than throw it to an error handling routine where it

4条回答
  •  伪装坚强ぢ
    2021-02-13 23:14

    This answer is my opinion on the problem at hand, perhaps viewed from a slightly different angle.

    When considering this block of code:

    On Error Resume Next
    personIndex = FindInArray(personName, personArray)
    If Err.Number = ERR__ELEMENT_NOT_FOUND_IN_ARRAY Then
        MsgBox "Name not found in person array. Using default person."
    Else
    End If
    

    You mention: "expected errors" in the title.
    But the thing is that no error should be thrown if you know in advance that it may occur.
    They are a form of validation that should in my opinion be built in into the functions in the form of conditional statements.

    The before mentioned code block would be something like this on a basic level:

        If Not (in_array(vArray, "Jean-Francois")) Then
            MsgBox "Name not found in person array. Using default person."
        End If
    

    Which in my opinion is a lot cleaner and readable.
    With a custom function that is not part of the base code, but that does your check behind the scenes. Reusable functions can be wrapped in a module that you use in a way that is very similar to a static class.

    Public Function in_array(vArray As Variant, sItem As String) As Boolean
    
        Dim lCnt As Long
    
        in_array = False
        Do Until lCnt = UBound(vArray) + 1
            If StrComp(vArray(lCnt), sItem, CompareMethod.Text) = 0 Then
                in_array = True
                Exit Function
            End If
            lCnt = lCnt + 1
        Loop
    
    End Function
    

    Even better would be to use the in_array() function from within the findInArray() function and have only 1 line of code in the basesub, which would be:

    personIndex = FindInArray(personName, personArray)
    

    Let the functions in the back handle the rest and intercept exceptions that you can foresee.
    This is only an example, obviously you write the functions and return values that are useful for you and you could probably add more extensive validation.

    My point is that these return values are return messages that are a part of the application / validation logic, I don't see them as technical errors - hence, I don't see any benefit in using an error handler for them as a custom created function exactly fits your needs in a (my opinion) much cleaner structure.

    I consider it a technical error when you pass for example three arguments into the function call while it only accepts two. The error handler notifies you, after which the developer may decide to make the current function more dynamic by allowing eg. optional parameters and fixing the bug.

提交回复
热议问题