Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to recover from COM error gracefully?

Tags:

c++

com

mfc

I have a third party COM component with its c++ interface in VC++. I am getting a crash in the call below which is crashing my application. How can I recover gracefully from this function which is not really part of my application?

inline _RecordsetPtr IGLibMgr::GetLibInfo ( _bstr_t LibPath ) {
    struct _Recordset * _result = 0;
    HRESULT _hr = raw_GetLibInfo(LibPath, &_result);
    if (FAILED(_hr)) _com_issue_errorex(_hr, this, __uuidof(this));
    return _RecordsetPtr(_result, false);
}

It crashes in the last line. I don't think I can modify this code since it's third party COM stuff. What options do I really have? I just want to bring up message box to user and return gracefully.

like image 657
zar Avatar asked Feb 11 '13 16:02

zar


Video Answer


1 Answers

If you're not already doing this in your code, you need to be from the caller-side:

try
{   // setup your invoke for your object...
    IGLibMgrPtr spMgr = ....
    bstr_t bstrPath = ....

    // invoke your call.
    _RecordsetPtr spRS = spMgr->GetLibInfo(bstrPath);

    ... continue normal processing ...
}
catch(const _com_error& ce)
{
    // handle your error here.
}

This is important on multiple levels. The most obvious being that not only can your IGLibMgr member throw an exception, so can the bstr_t allocation, etc. When using #import code from a COM DLL, get used to this format if using generated smart-pointers from the comutil library of MSVC.

Note: The _com_error class provides several members for obtaining why the error happened, including the HRESULT, error description string, etc. It even provides access to the IErrorInfo created by the error-returning object if it is so-nice as to provide that level of detail.

like image 60
WhozCraig Avatar answered Sep 20 '22 23:09

WhozCraig