Is there a “right way” to define error codes? I mean, I’ve built a library a while ago that throws custom exceptions, but I targeted the custom error messages to a developer’s standpoint. Now I’m wrapping up the GUI and when I catch those exceptions, I need more user friendly messages. That’s not a problem in itself, but let’s say, I have my ReceiverNotAvailableException exception and NoMessageReceivedException. To me, as a developer, they mean completely different things and have different inner messages, but to the end-user they just mean “User not found”. I’d like to display something like “User not found (error X)” where X varies depending on which exception is raised – pretty commonplace if you ask me.
My question is: should I go with X=1, 2 and so forth depending on what kind of exception or should I opt for something more complicated for whatever reason? I know it sounds like a dumb question, but I’d really like to know what the “best practice” (I’m not so fond of the term) is in this case.
BTW, of course I’d have a table mapping each code to its corresponding exception, whichever the case is.
If your exceptions can’t overlap, then going with a HashTable[ExceptionName] = “Error Message” looks like a sane option. If they can you can use something like the following:
The standard way to define message codes that can overlap (this is, occur at the same time) is to use powers of two:
and so on. Then, in code you can do
Finally, on the receiving end you can:
Explanation:
Then
and, on the checking code
Now, if you are using exceptions you can use the same approach, bubbling up the errorCode as long as exception occur. Although this idiom is more common in C.