Home > Backend Development > C++ > body text

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

Susan Sarandon
Release: 2024-11-19 20:38:03
Original
886 people have browsed it

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

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;
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template