Translate error codes to string to display

前端 未结 7 1251
无人共我
无人共我 2021-01-03 03:18

Is there a common way in C++ to translate an error code to a string to display it?

I saw somewhere a err2msg function, with a big switch, but is that re

7条回答
  •  礼貌的吻别
    2021-01-03 03:52

    I tend to avoid the switch since it's usually a big piece of code. I prefer a table lookup along the lines of:

    In btree.h:
        enum btreeErrors {
            ZZZ_ERR_MIN = -1,        
            OKAY,
            NO_MEM,
            DUPLICATE_KEY,
            NO_SUCH_KEY,
            ZZZ_ERR_MAX };
    
    In btree.c:
        static const char *btreeErrText[] = {
            "Okay",
            "Ran out of memory",
            "Tried to insert duplicate key",
            "No key found",
            "Coding error - invalid error code, find and destroy developer!"
        };
        const char *btreeGetErrText (enum btreeErrors err) {
            if ((err <= ZZZ_ERR_MIN) || (err >= ZZZ_ERR_MAX))
                err = ZZZ_ERR_MAX;
            return btreeErrText[err];
        }
    

    Not that it usually matters since errors should be the exception rather than the rule, but table lookups are generally faster than running big switch statements (unless they get heavily optimised).

提交回复
热议问题