Error Handling in C# / VBA COM Interop

六眼飞鱼酱① 提交于 2021-02-07 09:34:48

问题


I have a C# DLL being called from Excel VBA which I have exposed via a COM Callable Wrapper / COM Interop. I want to be able to pass any exceptions which occur in the C# code up onto the VBA client. Are there any recommended approaches to doing this ? Thanks.


回答1:


It is possible to create your own exceptions that communicate HRESULT error codes back to VBA or other COM based callers. Here's an example that uses E_FAIL:

public class ComMessageException : Exception
{
    public ComMessageException(string message)
        :base(message)
    {
        HResult = unchecked((int)0x80004005);
    }
}

Here is an MSDN article that describes the process.

This should give you the same VBA error support you had in VB6, it will display the error message of your choice to the user along with the HRESULT that you choose.




回答2:


Years ago I have vague memories of returning error information on COM function calls. COM functions should not return exceptions. The fact that an error happened in the COM function is signalled by the return value. S_OK (0) meant success. negative numbers meant failure. You could use different negative numbers to pass basic error types, however for more specific error information, you had to implement the IErrorInfo interface on the COM object.

Having done this, Visual Basic 6 and Visual Studio 2000 handled COM errors nicely in Visual Basic, however older versions of VBA didnt.

If someone has used COM much more recently they may well be able to fill in the details, and correct where my memory has gone hazy over the years.

It strikes me that implementing a new COM wrapper code that translated exceptions into documented COM errors would not be an easy generic thing and that making a hand coded version could be done, but again, you would need to understand COM programming.

Redesigning your .NET objects so they reported error detail by calling your getlasterror() method in your object would be a sensible workaround.



来源:https://stackoverflow.com/questions/4226397/error-handling-in-c-sharp-vba-com-interop

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!