Using GetLastError to Diagnose Win32 API Errors

Posted: (EET/GMT+2)

 

When programming Windows applications using the Win32 API, you will sometimes find that a function fails without giving much information about the reason. Many Windows API functions return a value which tells whether the operation was successful, but the actual error can be more difficult to find.

Fortunately, Windows provides a function called GetLastError(), which can be used to get additional information about a failed API call.

For example, the DeleteFile() function returns zero if the file could not be deleted. We can then call GetLastError() to find out what happened:

if (!DeleteFile("C:\\TEMP\\TEST.TXT"))
{
    DWORD error = GetLastError();
    printf("Error code: %lu\n", error);
}

The returned value is a numeric error code. For example, error 2 means that the specified file could not be found, while error 5 means that access was denied.

To make these numbers easier to understand, Windows also provides the FormatMessage() function, which can convert many system error codes into readable messages.

DWORD error = GetLastError();
char message[256];

if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM |FORMAT_MESSAGE_IGNORE_INSERTS, NULL,
    error, 0, message, sizeof(message), NULL))
{
    printf("Windows error: %s\n", message);
}

One important thing to remember is that GetLastError() should be called immediately after the API function has failed. Other Windows API calls may change the last error value, so waiting too long can give you incorrect information.

Also, not every API function uses GetLastError() in the same way. Always check the documentation to see how a function reports errors. A successful call doesn't necessarily clear the previous error code.

When debugging Win32 applications, GetLastError() and FormatMessage() are very useful tools. Instead of guessing why an operation failed, you can often ask Windows for the reason.

For more information, see the Microsoft Win32 SDK documentation for GetLastError and FormatMessage.

Hope this helps!