Translate error codes to string to display

前端 未结 7 1346
无人共我
无人共我 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:47

    Since C++ does not allow automatic 'translation' from enum values to enum names or similar, you need a function to do this. Since your error codes are not somehow defined in your O/S you need to translate it by yourself.

    One approach is a big switch statement. Another is a table search or table lookup. What's best depends on error code set.

    table search can be defined in this way:

    struct {
        int value;
        const char* name;
    } error_codes[] = {
        { ERR_OK, "ERR_OK" },
        { ERR_RT_OUT_OF_MEMORY, "ERR_RT_OUT_OF_MEMORY" },
        { 0, 0 }
    };
    
    const char* err2msg(int code)
    {
        for (int i = 0; error_codes[i].name; ++i)
            if (error_codes[i].value == code)
                return error_codes[i].name;
        return "unknown";
    }
    

提交回复
热议问题