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?
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.
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.";
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With