How to embed an error code in a standard function return

By | 2019-08-25

I have read many accounts in various books and articles about how it would be nice to be able to return an error code with every function return.

It’s fairly easy to achieve this. Simply create a User-Defined-Type (or class) called tReturn (or whatever) in a global module (assuming the use of a UDT).

'---------------------------------------------
Type tReturn
    Value as Variant
    Error as Integer
End Type
'---------------------------------------------

Creating a class (which I personally prefer utilizing in my own code) allows for fairly sophisticated error handling by embedding functions within the class to resolve the errors without needing to stick alot of error-handling code all over the place.

Usage

Make each function of type tReturn.

'---------------------------------------------
Public Function MyFunc(arg1, arg2) as tReturn
'---------------------------------------------

When coding the function body, if an error occurs simply assign a non-zero value to the “.Error” item in the return value

'---------------------------------------------
Public Function MyFunc(arg1, arg2) as tReturn
   ...
   MyFunc.Error = 5 'Some Error
          (or)
   MyFunc.Error = Err
   ...
End Function
'---------------------------------------------

This way, you can always tell if an error has occured by checking the existence of an error in the return value

'---------------------------------------------
   Dim MyReturn as tReturn
   ...
   MyReturn = MyFunc(3,8)
   If Not MyReturn.Error Then
      nSomeVariable = MyReturn.Value
   End If
   ...
'---------------------------------------------

If you create tRetrun as a class (cReturn or whatever), you can make .Value as the default property and code it this way:

'---------------------------------------------
   Dim MyReturn as New cReturn
   ...
   MyReturn = MyFunc(3,8)
   If Not MyReturn.Error Then
      nSomeVariable = MyReturn
   End If
   ...
'---------------------------------------------

Author: dwirch

Derek Wirch is a seasoned IT professional with an impressive career dating back to 1986. He brings a wealth of knowledge and hands-on experience that is invaluable to those embarking on their journey in the tech industry.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.