Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Translate error codes to string to display

Tags:

c++

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?

like image 796
Karl von Moor Avatar asked Oct 20 '10 06:10

Karl von Moor


2 Answers

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";
}
like image 159
harper Avatar answered Sep 27 '22 23:09

harper


In windows you can use FormatMessage(...) function either with error code return by GetLastError() function or directly to the suspected area.

Please see below links for examples.

http://msdn.microsoft.com/en-us/library/ms679351(v=VS.85).aspx

http://msdn.microsoft.com/en-us/library/ms680582(v=VS.85).aspx

I hope this will help you.

like image 35
user001 Avatar answered Sep 28 '22 00:09

user001