c++comhresultextract-error-message

Retrieving error message from HRESULT in C++ after calling a C# COM object


I have a COM object written in C#. Under some circumstances, the COM object may throw an Exception with a descriptive message if it encounters an error (for example throw new Exception("error message")).

This COM object is called from VB6 code and from C++ code.

From the VB6 code, I can retrieve the error message using Err.Message.

In C++, I get an HRESULT 0x80131500 as specified in the System.Exception documentation.

Once I have this HRESULT in C++, how can I get the error message of the Exception (Exception.Message) like the message returned by Err.Message in VB6?

I searched the web and found a few examples using FormatMessage and _com_error, but none of these return the message I want.


Solution

  • Updated.

    Try to QueryInterface the failing object for the ISupportErrorInfo interface, then call the InterfaceSupportsErrorInfo method with the REFIID of the interface throwing the exception. If it returns S_OK, then just calls the GetErrorInfo function to get an IErrorInfo interface. Then use the GetDescription method.