Home  >  Article  >  Backend Development  >  How Can I Convert Windows GetLastError() Error Codes into Human-Readable Textual Messages?

How Can I Convert Windows GetLastError() Error Codes into Human-Readable Textual Messages?

DDD
DDDOriginal
2024-11-19 15:29:02549browse

How Can I Convert Windows GetLastError() Error Codes into Human-Readable Textual Messages?

Retrieving Textual Error Messages from GetLastError() Error Codes

When performing Windows API calls, the GetLastError() function provides an integer-valued error code indicating any encountered issues. To obtain a more informative error message, follow these steps:

1. Utilize FormatMessageA:

The FormatMessageA function allows you to convert an error code into a textual error message. It requires the following parameters:

  • FORMAT_MESSAGE_ALLOCATE_BUFFER: Allocates a buffer to store the message.
  • FORMAT_MESSAGE_FROM_SYSTEM: Uses system-supplied error messages.
  • FORMAT_MESSAGE_IGNORE_INSERTS: Ignores message modifiers (e.g., "%1").
  • NULL: Indicates that the message will be formatted without any parameters.
  • &messageBuffer: Pointer to the allocated buffer for the message.

2. Invoke the Function:

Call FormatMessageA with the appropriate parameters, including the error code:

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);

3. Copy and Free the Error Message:

After retrieving the message, copy its contents into a string and free the Win32's allocated buffer:

std::string message(messageBuffer, size);
LocalFree(messageBuffer);

By following these instructions, you can obtain a detailed error message in textual form from the error code returned by GetLastError(), enhancing your understanding of encountered issues during Windows API calls.

The above is the detailed content of How Can I Convert Windows GetLastError() Error Codes into Human-Readable Textual Messages?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn