Search code examples
.neterror-handlingcom-interop

Handling or Passing Errors From .NET Assembly to COM Client/Consumer


I'm programming a COM Interop .NET Assembly (a COM Callable Wrapper) and I'm trying to understand what the correct way is to pass errors that occur in a .NET Assembly to the COM client/consumer. I'm not sure that this changes my question very much but this particular .NET assembly is taking an existing open source FTP library and exposing a subset of it's abilities to COM. For the most part it's a simple, "dumb" wrapper.

I'm guessing that the best way to program the error handling is to have public OnError event inside the .NET assembly that the COM client/consumer can use to subscribe to error events. Then it would be up to the one programming in COM to decide whether or not to use the event and what to do with it. This could be somewhat dangerous because the COM programmer could omit the error event handler and have no awareness of errors occurring within the .NET Assembly. Because this .NET Assembly is supposed to be quite generic, I'm pretty sure I don't want the .NET assembly bringing up message boxes or handling errors in some other way in which the COM consumer has little or no control.

Is there a better way to handle this or some standard way?


Solution

  • Do this the standard .NET way, throw an exception. The CCW wrapper catches it and translates it to the HRESULT code that any COM method returns. It also implements IErrorInfo so that the COM client can get a good description of the error, don't forget to pass one in the exception constructor unless it is an obvious exception. They rarely are by the time they get translated btw.

    Do try to use standard .NET exception types as much as possible. They all have their own HResult property value already preset, mapping to a COM error code as best as possible. If you need a custom HRESULT then use the COMException(string, int) constructor.