Getting information on a COM failure

Nothing terribly deep here, but after a long time without writing new code using COM, I had to remember that there’s a GetErrorInfo method. Here’s a quick reminder of how to get more information on a COM method failure.

{
  // Snippit… Assume you’ve got a pointer pCOMObject with
  // method Foo and that COM is happily initialized, etc…

  // The FAILED macro returns true if the HRESULT returned
  // by the operation is negative, indicating a failure
  if FAILED(pCOMObject->Foo())
    DisplayError();

  // Don’t forget to clean up
  pCOMObject->Release();
  CoUninitialize ();
}

DisplayError()
{
   LPERRORINFO pErrorInfo=NULL;
   // GetErrorInfo returns a pointer to the most recently set
   // IErrorInfo pointer in the current logical thread. It also
   // transfers ownership of the error object to the caller,
   // and clears the error state for the thread.

   GetErrorInfo(0,&pErrorInfo);
   BSTR strDescription, strSource;
   pErrorInfo->GetDescription (&strDescription);
   pErrorInfo->GetSource(&strSource);

   // Display or log error appropriately, not this way
   _tprintf(TEXT(“%s\n”),strDescription);
   _tprintf(TEXT(“%s\n”),strSource);

   // Clean up
   pErrorInfo->Release();
   SysFreeString(strDescription);
   SysFreeString(strSource);
}

http://blogs.msdn.com/greggm/archive/2004/11/24/269378.aspx – Debugging tips
http://blogs.msdn.com/adam_nathan/archive/2003/06/13/56713.aspx – Gotchas
http://blogs.gotdotnet.com/anathan/PermaLink.aspx/6d021f27-72c8-4420-b6ad-1c5f0690bde8 – Win32/.NET Interop tips

Leave a Reply