How to wrap errors when calling COM in C ++?

To follow the normal COM procedure, whenever an error occurs, you must do the following:

  • Check HRESULTon FAILEDor similar to see if an error has occurred.
  • Create a variable to store IErrorInfo(usually CComPtr<IErrorInfo>)
  • Challenge ::GetErrorInfo(0, &var).
  • Get the human-readable version by calling IErrorInfo::GetDescription.
  • Convert BSTRto std::wstring.
  • Convert std::wstringto some form char const*.
  • Throw a user-defined type of exception derived from std::exceptionthat exposes bits 1, 5, and 6 above.

All this looks like a lot of patterns that should be executed in almost all function calls in COM.

I know that the MSVC ++ compiler provides a whole bunch of things to facilitate communication with COM, such as ATL, and compiler-specific COM extensions _com_error, _com_raise_errorand the like, but I'm not sure how to use them, or if they are even designed to be used in user code.

Are there any typical strategies that are used to manage this difficulty in a safe, safe, and secure race mode?

+3
source share
2 answers

The "obvious" solution is ComException. It can handle almost all the steps - you just need to get HRESULTfor ctor and discard the received object (steps 1 and 7).

You can even write

HRESULT check(HRESULT hr)
{
  if(FAILED(hr)) throw ComException(hr);
  return hr; // Success comes in different forms. 
}

to take care of step 7 for you. For instance.check(pUnk->QueryInterface(MyID, &pMyIf));

+4

, , api- msdn, , HResult, , IPtr .. , , , .

+1

All Articles