monkeydeus
monkeydeus

Reputation: 395

Handling .net Errors in COM

I have to create a dll to enable legacy clients to continue to use COM to access the middle tier. The new middle tier uses WCF/.net 4.5, so I will be exposing a .net 4.5 dll via COM.

My question is how to return errors/what to return when an error occurs. I am finding very little information about this. There is currently no error-handling in the existing clients that I can find, so I can't use that as a benchmark.

Can I just use the standard try/catch approach, throw a .net error, and let the client sort it out, or is there something more I need to do to enable error handling in this kind of scenario?

Upvotes: 1

Views: 106

Answers (1)

Hans Passant
Hans Passant

Reputation: 941327

This is not a minor detail, unfortunately. It is certainly not uncommon for COM client code to look at the return HRESULT and react to specific values. Could be a bug workaround, could be customized error reporting, could be an "expected to fail, let's do this then" code flow. How intricate that kind of code got has a lot to do with how long the COM component has been around and how troublesome it used to be.

But yes, very hard to reverse-engineer. Do try to find the opportunity to interview a client code programmer and just ask what he does. And review your original code. Wherever you returned a specific HRESULT before, you want to make sure you do that again in your .NET replacement. Use Marshal.ThrowExceptionForHR().

.NET itself otherwise has excellent support for good COM error reporting. Any exception you throw in a [ComVisible] class method is automatically caught and mapped to an HRESULT that's returned to the caller. The CLR implements IErrorInfo so that the client can get rich error info that includes a textual description of the error beyond just the HRESULT. So the Exception.Message doesn't have to get lost, assuming the client uses the interface.

Every standard .NET Exception derived object maps to a specific HRESULT with a logical mapping, as far as COM allows. Like OutOfMemoryException maps to E_OUTOFMEMORY, ArgumentException maps to ERROR_INVALID_PARAMETER, IOException maps to the original winapi error code, etcetera. Even if the client code only ever displays or logs the HRESULT then there is still a way to map it back to the original .NET exception.

But without the Holy Stack Trace of course, do consider logging that. Very painful to write that try/catch/throw code but absolutely invaluable when the chips are down. They will be down.

Upvotes: 2

Related Questions