3

Say, if I have a WinAPI that fails with an HRESULT code. Is there a way to convert it to an error description string?

c00000fd
  • 20,994
  • 29
  • 177
  • 400
  • 1
    For many codes you can do `FormatMessage`, for some there is no way to get text, some even overlap (same codes with API specific meaning - see [`FACILITY_ITF`](http://msdn.microsoft.com/en-us/library/windows/desktop/ms679751%28v=vs.85%29.aspx)). Hence there is no simple answer. Or, you might narrow down the question to specific API you are interested in. – Roman R. Mar 06 '14 at 19:05
  • 1
    A quick Google search would have given you [this](http://stackoverflow.com/questions/7008047/is-there-a-way-to-get-the-string-representation-of-hresult-value-using-win-api). –  Mar 06 '14 at 19:08
  • 1
    Yes, `_com_error` seems to be the way to do it too. Thanks. What is interesting is that internally it uses `FormatMessage` on the `HRESULT` just as if it was the error code from `GetLastError`. Hmm. – c00000fd Mar 06 '14 at 19:21

1 Answers1

5

This is the helper function we use in-house to extract a Win32 error code from an HRESULT:

DWORD Win32FromHResult(HRESULT hr)
{
    if ((hr & 0xFFFF0000) == MAKE_HRESULT(SEVERITY_ERROR, FACILITY_WIN32, 0))
    {
        return HRESULT_CODE(hr);
    }

    if (hr == S_OK)
    {
        return ERROR_SUCCESS;
    }

    // Not a Win32 HRESULT so return a generic error code.
    return ERROR_CAN_NOT_COMPLETE;
}

You can then use FormatMessage to get it into string form.

Jonathan Potter
  • 36,172
  • 4
  • 64
  • 79