How can I (is there a way to) convert an HRESULT into a system specific error message?

前端 未结 1 1622
滥情空心
滥情空心 2020-12-29 13:05

According to this, there\'s no way to convert a HRESULT error code into a Win32 error code. Therefore (at least to my understanding), my use of FormatMessage in order to gen

相关标签:
1条回答
  • 2020-12-29 13:45

    This answer incorporates Raymond Chen's ideas, and correctly discerns the incoming HRESULT, and returns an error string using the correct facility to obtain the error message:

    /////////////////////////////
    // ComException
    
    CString FormatMessage(HRESULT result)
    {
        CString strMessage;
        WORD facility = HRESULT_FACILITY(result);
        CComPtr<IErrorInfo> iei;
        if (S_OK == GetErrorInfo(0, &iei) && iei)
        {
            // get the error description from the IErrorInfo 
            BSTR bstr = NULL;
            if (SUCCEEDED(iei->GetDescription(&bstr)))
            {
                // append the description to our label
                strMessage.Append(bstr);
    
                // done with BSTR, do manual cleanup
                SysFreeString(bstr);
            }
        }
        else if (facility == FACILITY_ITF)
        {
            // interface specific - no standard mapping available
            strMessage.Append(_T("FACILITY_ITF - This error is interface specific.  No further information is available."));
        }
        else
        {
            // attempt to treat as a standard, system error, and ask FormatMessage to explain it
            CString error;
            CErrorMessage::FormatMessage(error, result); // <- This is just a wrapper for ::FormatMessage, left to reader as an exercise :)
            if (!error.IsEmpty())
                strMessage.Append(error);
        }
        return strMessage;
    }
    
    0 讨论(0)
提交回复
热议问题