In the process of creating a module I am facing a dilemma: should each class internally define its own error codes, or should there be a module-wide error codes defined?
So far pros and cons go hand-in-hand, but I am inclined to define per-class errors:
1:
class MyClass
{
public:
typedef enum _TResult {
EOk = 0,
EErrNoMemory,
EErrBadParam,
<...>
} TResult;
TResult DoSomething();
};
As opposed to something like:
2-1:
#define OK (0)
#define ERR_NO_MEMORY (1)
#define ERR_BAD_PARAM (2)
Or:
2-2:
typedef enum _TResult
{
EOk,
EErrNoMemory,
EErrBadParam,
<...>
EErrTimeOut,
EErrFeedThePenguin
} TResult;
From your experience what would be the gotcha’s for any of the approaches?
The one thing that I’d comment about with per-class error codes is that you then aren’t able to write a single error logger (or at least not easily) due to the fact that the same code will mean different things depending on the class.
That said, you can always use both. Have a global enum with common errors:
and then in classes you can have:
Which gives you a place for global error codes and ensures your class error codes won’t overlap the globals (and this is maintained by the compiler).