COM Exceptions in C #
I am consuming a cpp COM object from C # code. My C # code looks like this:
try
{
var res = myComServer.GetSomething();
}
catch (Exception e) { }
However, the exception never contains any of the details set in cpp, in particular my error message.
In my cpp side, I followed several examples I found on the internet:
...
ICreateErrorInfo *pcerrinfo;
IErrorInfo *perrinfo;
HRESULT hr;
hr = CreateErrorInfo(&pcerrinfo);
pcerrinfo->SetDescription(L"C++ Exception");
hr = pcerrinfo->QueryInterface(IID_IErrorInfo, (LPVOID FAR*) &perrinfo);
if (SUCCEEDED(hr))
{
SetErrorInfo(0, perrinfo);
perrinfo->Release();
}
pcerrinfo->Release();
return E_FAIL; // E_FAIL or other appropriate failure code
...
Did I miss something? Is there anything else that might affect this, such as marshaling, interop creation, or attributes of the COM server itself?
a source to share
Assuming your class implements ISupportErrorInfo
, did you accidentally add support AFTER you imported the library into your C # project from Visual Studio?
Visual Studio generates the gunk that is required to communicate with the COM library only once, when you import the library. To this end, it creates a special translation library called "originalDllName.Interop.dll" based on the information available in the DLL's TypeLib during import.
You can make changes to the implementation as often as you like without any problem; but if you change the library in any way (add new classes, change interface definitions, change the iterations implemented by your classes ...), you will have to remove the COM DLL from your references and then re-import it to update the Interop library.
a source to share
Instead of catching type Exception, catch COMException type like this ...
try
{
// COM call
}
catch( COMException cEx )
{
// Check HRESULT here
}
a source to share