COM error handling best practice

COM error handling best practice

COM:

COM stands for Component Object Model is a binary-interface standard for software components introduced by Microsoft in 1993. It is used to enable inter-process communication object creation in a large range of programming languages.

Most of the COM functions and interface methods return a value of the type HRESULT which is really frustrating for a developer. HRESULTs are really not handles to anything; they are only values with several fields encoded in the value. As per the COM specification, a result of zero indicates success and a nonzero result indicates failure.

At the source code level, all error values consist of three parts, separated by underscores. The first part is the prefix that identifies the facility associated with the error, the second part is E for error, and the third part is a string that describes the actual condition. For example, STG_E_MEDIUMFULL is returned when there is no space left on a hard disk. The STG prefix indicates the storage facility, the E indicates that the status code represents an error, and the MEDIUMFULL provides specific information about the error. Many of the values that you might want to return from an interface method or function are defined in Winerror.h.

How to return error information?

Using the COM error-handling interfaces and functions, you can return error information by performing the following the steps:

  1. Implement the ISupportErrorInfo interface.
  2. To create an instance of the generic error object, call the CreateErrorInfo function.
  3. To set its contents, use the ICreateErrorInfo methods.
  4. To associate the error object with the current logical thread, call the SetErrorInfo function.

ISupportErrorInfo

public void InterfaceSupportsErrorInfo (ref Guid& riid);

CreateErrorInfo

HRESULT CreateErrorInfo(
  ICreateErrorInfo **pperrinfo
);

pperrinfo [Out] . Address where error information creation object will be stored.

Result

Success: S_OK.
Failure: HRESULT code.

SetErrorInfo

HRESULT SetErrorInfo(
  ULONG      dwReserved,
  IErrorInfo *perrinfo
);

dwReserved [in] Reserved for future use; must set to zero.
perrinfo [in] Pointer to an error object that supports IErrorInfo.

Success: S_OK.
Failure: HRESULT code.

Leave a Reply

Your email address will not be published. Required fields are marked *