How to Interpret Error Codes Returned by GetLastError()
After invoking a Windows API call, developers may encounter error situations where understanding the underlying reason for the failure is crucial. The native Win32 API function GetLastError() provides an error code, but this code is represented as an integer, making it difficult to decipher its meaning.
Converting Error Codes to Textual Messages
To obtain a human-readable error message, developers require a mechanism to convert these numerical error codes into textual descriptions. The code snippet below showcases this conversion process:
#include <windows.h> #include <string> std::string GetLastErrorAsString() { // Retrieve the error message ID, if available. DWORD errorMessageID = ::GetLastError(); if (errorMessageID == 0) { return std::string(); // No error message has been recorded. } LPSTR messageBuffer = nullptr; // Instruct Win32 to generate the message string for the provided error ID. 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); // Transfer the error message into a std::string. std::string message(messageBuffer, size); // Deallocate Win32's message buffer. LocalFree(messageBuffer); return message; }
Usage:
To utilize this function, simply call GetLastErrorAsString() after any API call that may return an error code. It will return a std::string containing the textual error message, which can then be displayed to the user or logged for further diagnostics.
The above is the detailed content of How Can I Convert Windows GetLastError() Error Codes into Human-Readable Messages?. For more information, please follow other related articles on the PHP Chinese website!