我如何(有办法)将 HRESULT 转换为系统特定的错误消息?

2023-11-25

根据this,没有办法将 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);
}

) 不适用于 HRESULT。

如何为 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;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

我如何(有办法)将 HRESULT 转换为系统特定的错误消息? 的相关文章

随机推荐