Home > Article > Backend Development > How to Translate Windows API Error Codes into Human-Readable Text Messages?
How to Retrieve Textual Error Messages from Error Codes in Windows API
In the Windows API, the GetLastError() function returns an integer error code that indicates the outcome of a system call. To obtain a human-readable error message corresponding to this code, we can employ the following techniques:
Method 1: Using the FormatMessage() Function
The FormatMessage() function provides a convenient way to convert error codes into text messages. It takes several parameters:
Example Code:
//Returns the last Win32 error, in string format. Returns an empty string if there is no error. std::string GetLastErrorAsString() { //Get the error message ID, if any. DWORD errorMessageID = ::GetLastError(); if(errorMessageID == 0) { return std::string(); //No error message has been recorded } LPSTR messageBuffer = nullptr; //Ask Win32 to give us the string version of that message ID. //The parameters we pass in, tell Win32 to create the buffer that holds the message for us (because we don't yet know how long the message string will be). size_t size = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, errorMessageID, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&messageBuffer, 0, NULL); //Copy the error message into a std::string. std::string message(messageBuffer, size); //Free the Win32's string's buffer. LocalFree(messageBuffer); return message; }
The above is the detailed content of How to Translate Windows API Error Codes into Human-Readable Text Messages?. For more information, please follow other related articles on the PHP Chinese website!