Translate error codes to string to display

c++

Solution

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";
}

Problem

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 really the best way?

Original source

Related problems