Generate diagnostic message for HRESULT codes?

2019-04-17 04:17发布

问题:

I'd like to be able to do the equivalent of FormatMessage - generate a text message for debug and even runtime builds that can report some of the common HRESULTs, or even spit out things like what the severity is, what facility it was, and possibly a description of the error code.

I found this simple function, but its too simple, and mostly seems to generate "unknown error". But so far I haven't found anything that looks more promising.

I can do something like the following:

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
        Append(bstr);

        // done with BSTR, do manual cleanup
        SysFreeString(bstr);
    }
}
else if (HRESULT_FACILITY(hr) == FACILITY_WIN32)
{
    // append the description to our label
    Append(CErrorMessage(HRESULT_CODE(hr)).c_str());
}

However, I wonder if I'm accomplishing anything more than _com_error.

Does anyone know of a reasonably fleshed out facility for generating error log output for HRESULTs?

回答1:

As you muse, _com_error::ErrorMessage() should do the trick.

If you are getting "Unknown Error", then the HRESULTs you are getting are probably not known to windows. For those messages, try dumping the HRESULT value and figuring out if they actually map to win32 error codes.

There are some com macros available to help you split out the bits of the HRESULT.



回答2:

If you are using WIN32 directly, the FormatMessage() call should help you out.



回答3:

Are you using Boost? The boost::system library will automatically look up HRESULT and Win32 API result codes.



标签: c++ windows com