Let's say I have a bunch of error codes in my application header.h
like:
#define SOMETHING_WENT_WRONG -1
#define SOLAR_FLARE_DECTECTED -2
#define ANTS_IN_YOUR_CPU -3
I return these as int
from various API functions. I'd like a clean way to offer a function that user can call to map these to more descriptive error messages, while keeping the header short.
That is, while I could always do something like:
const char *getErrorMessage(int errCode) {
switch (errCode) {
case SOMETHING_WENT_WRONG:
return "Something bad happened, but I don't know more than that";
case SOLAR_FLARE_DECTECTED:
return "A solar flare, rather than programmer error, has caused a malfunction";
case ANTS_IN_YOUR_CPU:
return "Ants have nested in your CPU, causing all ALU functions to fail";
default:
return "I heard you like errors in your error handling. So ...";
}
}
I really want to avoid the duplication of mentioning the error macro twice (DRY), and having the definition and error string in two different places (making it non-obvious that those adding an error code also need to update the error function).
So I'm looking for an approach that only uses 1 line(ish) per error code - the macro name, int
error code and message all together.
Bonus points if I can leave the error string off and have the error string just be the stringified macro name (e.g., "SOMETHING_WENT_WRONG"
for the first error).
I'm not too worried about lookup performance, so it's fine for example, to build an array and look through it in the lookup function.
strcmp
rather than==
, and I depending on how the strings were used, I may not be able to change the string text in the future. Also, if I'm still using#define SOME_ERROR "some error"
pattern, the linker may or may not combine the identical strings, which can cause linker-dependent behavior if people do compare the pointers, an so on.