Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return an error message string

I have written a driver in C++ for a peripheral device and in short, there is a number of errors that can occur during interaction. I have defined error codes for all the possible errors. I want to write a method that enables the user to query the meaning of error code.

Bear in mind that I have a total of 17 possible errors. The corresponding messages are of varying lengths.

I have solved it with a function that accepts the error code and returns a string with the error message. The function uses the error code to loop through a switch case routine each case returning a different error message as shown below.

std::string getErrorMessage(int errorCode)
{
    std::string errorMessage = "no error" ;

    switch(errorCode) {
    case 0:
        errorMessage = "no error" ;
        break ;
    case 10:
        errorMessage = "there is a network error" ;
        break ;
    case 40:
        errorMessage = "there is a network or protocol error" ;
        break ;
    default:
        errorMessage = "unknown error" ;
    }

    return errorMessage ;
}

This function works, but it's not a "pretty" solution. Does anyone have any ideas or suggestions for a better solution?

like image 829
meltnot Avatar asked Dec 09 '22 11:12

meltnot


2 Answers

If your error number is not large, using a table is more efficient

char *error[SIZE] = 
 {
   [0] = "NO error",
   [10] = "there is a network error",
   [40] = "there is a network or protocol error",
    ....
}

You need some defensive check to make sure the error number is in range.

This is how glibc implments strerror() as I can recall.

like image 174
tristan Avatar answered Dec 20 '22 01:12

tristan


You could use std::map<int, std::string> for mapping error messages to according codes:

std::string getErrorMessage(int errorCode)
{
    static std::map<int, std::string> codes;
    static bool initialized = false;
    if (!initialized) {
        codes[0]    = "No error.";
        codes[10]   = "Network error.";
        codes[40]   = "Network or protocol error.";
        initialized = true;
    }
    if (codes.count(errorCode) > 0)
        return codes[errorCode];
    return "Unknown error.";
}
like image 27
LihO Avatar answered Dec 20 '22 01:12

LihO