How to convert HRESULT into an error description?

c00000fd picture c00000fd · Mar 6, 2014 · Viewed 8.2k times · Source

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

Answer

Jonathan Potter picture Jonathan Potter · Mar 6, 2014

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.