Search code examples
c++errnostrerror

Redefining a predefined errno error message (E2BIG)


Is there a way to redefine errno error messages? For example, I am working with E2BIG and I am wanting to change the error message it shows when the error is encountered.

These messages are stored as an int, so when I redefine it will only let me change its integer value which is not very useful. I am wanting to change the message itself.

#include <string>
#include <iostream>
#include <vector>

int main() 
{
   const std::size_t BUF_SIZE = 256;
   std::vector<char> buffer(BUF_SIZE);
   int errNum = E2BIG;

   auto strerror = strerror_s(buffer.data(), buffer.size(), errNum);

   std::cout << buffer.data();
}

The current error message is:

Arg list too long

But I am trying to change it to say something a bit different. Is there a way to do this?


Solution

  • You'll need to write a wrapper function to fill in any custom error messages you need. For example:

    errno_t my_strerror_s(char *buffer, size_t numberOfElements, int errnum)
    {
        if (errnum==E2BIG) {
            const char *msg = "my custom error";
            if (numberOfElements < strlen(msg)+1) {
                return -1;
            else {
                strcpy(buffer, msg);
                return 0;
            }
        } else {
            return strerror_s(buffer, numberOfElements, errnum);
        }
    }