c++winapierror-handlingstandardsgetlasterror

Handling WinAPI error return values


I am currently learning C++ in connection with WinAPI. I am struggling to come up with meaningful error handling strategy for WinAPI functions.

PROBLEM:

Most of WinAPI functions can return 0 in case of error, but in many cases I don't see any information on MSDN as to what could cause such error and how to address / resolve it. Taking GetCursorPos as an example:

Returns nonzero if successful or zero otherwise. To get extended error information, call GetLastError.

(...)

The input desktop must be the current desktop when you call GetCursorPos. Call OpenInputDesktop to determine whether the current desktop is the input desktop. If it is not, call SetThreadDesktop with the HDESK returned by OpenInputDesktop to switch to that desktop.

If the function fails, the return value is NULL. To get extended error information, call GetLastError.

To sum it up: almost every function in WinAPI can return value determining occurrence of error and I can get information on the error when it happens using GetLastError function. But no information whatsoever on what kinds of errors I can expect and what steps to make to resolve them.

The examples are many, GetWindowRect is also widely used and MSDN delivers the very same limited information as for GetCursorPos.

QUESTION:

Please are there any standards on how to approach WinAPI function error return values that would retain error handling from becoming just showing a message box and exiting the application? Thank you!


Solution

  • As far as knowing ahead of time what possible error codes can be returned by a particular function, I'm afraid that Microsoft decided long time ago that maintaining such documentation for all functions would be too cumbersome and costly, as an API function may call any number of other API functions, which in turn may call others and so on. Sometimes you get lucky and the MSDN doc calls out error codes specific to that function, as is the case with ReadFile but this is not the case with all functions as you have noticed.

    That being said, the standard way of dealing with the error codes returned by GetLastError() is to format them with FormatMessage.

    If you passed LANG_USER_DEFAULT for lang ID, this will return the sometimes helpful, sometimes not so helpful error message formatted in the user's chosen locale from the error code. You can show this message to the user. If you wanted to format it in your own language for logging purposes, assuming it's English, you would pass MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US) for lang ID.

    And this is the best you can do if the error codes are not documented and you haven't come across them in testing: log them and get the log with other debug info attached to the issue report.