簡體   English   中英

我怎樣才能(有辦法)將HRESULT轉換為特定於系統的錯誤消息?

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

根據這個 ,沒有辦法到HRESULT錯誤代碼轉換為Win32錯誤代碼。 因此(至少對我的理解),我使用FormatMessage來生成錯誤消息(即

std::wstring Exception::GetWideMessage() const
{
    using std::tr1::shared_ptr;
    shared_ptr<void> buff;
    LPWSTR buffPtr;
    DWORD bufferLength = FormatMessageW(
        FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
        NULL,
        GetErrorCode(),
        0,
        reinterpret_cast<LPWSTR>(&buffPtr),
        0,
        NULL);
    buff.reset(buffPtr, LocalFreeHelper());
    return std::wstring(buffPtr, bufferLength);
}

)不適用於HRESULTs。

如何為HRESULT生成這些特定於系統的錯誤字符串?

這個答案結合了Raymond Chen的想法,並正確識別傳入的HRESULT,並使用正確的工具返回錯誤字符串以獲取錯誤消息:

/////////////////////////////
// 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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM