开发者

.Net com server catch unhandled exception

I've开发者_运维百科 created a Com server in C#. The project type is class library. Is there a way to get en event for unhandled exceptions in my code? I've tried AppDomain.CurrentDomain.UnhandledException without any luck


Not possible. The COM interop support code in the CLR implements the restriction in COM that exceptions are not allowed to escape from a COM method. Your method will be called with a catch-all exception handler inside the CLR that catches any exception you throw. It gets translated to a COM error code, an HRESULT, the return value of any COM Automation compatible interface method. The value of Exception.HResult. The COM client code uses that value to determine if the method call failed.

You can otherwise use the debugger and make it stop on any exceptions. Debug + Exceptions, tick the Thrown checkbox. The debugger automatically breaks on the 'first chance' exception.


Because this isn't possible as described in Hans Passant's answer, and because useful information such as the Stack Trace is lost when an Exception is converted to a COM HRESULT, I often use explicit interface implementation to ensure exceptions are logged when my ComVisible library is called from a COM client. A bit of work, but COM interfaces tend to be stable so it's only done once.

E.g.:

[ComVisible(true)]
public interface IMyClass
{
    void MyMethod();
    ...
}

[
ComVisible(true),
ClassInterface(ClassInterfaceType.None)
]
public MyClass : IMyClass
{
    ...

    public MyMethod()
    {
        ... implementation 
    }

    void IMyClass.MyMethod()
    {
        try
        {
            this.MyMethod();
        }
        catch(Exception ex)
        {
            _logger.Log(ex);
            throw;
        }

    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜