简体   繁体   English

调用WCF回调方法时的正确异常处理

[英]Proper exception handling when invoking WCF callback method

I have a series of WCF services that invoke methods on the client again (using WcfDuplexChannels) based on events at the server side. 我有一系列WCF服务,它们基于服务器端的事件再次调用客户端上的方法(使用WcfDuplexChannels)。 However, it seems there are quite some exceptions that can occur, so right now I have a huge try/catch block around every line calling back to the client, ending with disabling of the event in case any exception occurs. 但是,似乎有很多异常可能发生,所以现在我在每行调用客户端的行周围都有一个巨大的try / catch块,最后以禁用事件的方式发生任何异常。 Besides being cumbersome to write every time, I'm not sure if I could simplify the try catch block by catching just a few base exceptions? 除了每次都麻烦写之外, 我不确定是否可以通过捕获一些基本异常来简化try catch块? Right now I don't really care what's causing the exceptions (I don't care whether it's faulted, aborted, disposed or timed out) but I do log the different exceptions. 现在,我真的不在乎是什么引起异常的(我不在乎它是有故障的,中止的,被处置的还是超时的),但是我确实记录了不同的异常。

I also read about IErrorHandler, but will that actually be suitable when invoking a method on the client? 我还阅读了有关IErrorHandler的信息,但是在客户端上调用方法时,这实际上是否合适?

Here's a sample of my current strategy: 这是我目前的策略示例:

    private void OnProductChanged(List<DTO> products)
    {
        try
        {
            client.OnProductChanged(products);
            return;
        }
        catch (TimeoutException)
        {
            log.Info("Communication to client timed out.");
        }
        catch (CommunicationObjectAbortedException)
        {
            log.Info("Connection to client is in aborted state.");
        }
        catch (CommunicationObjectFaultedException)
        {
            log.Info("Connection to client is in faulted state.");
        }
        catch (CommunicationException ce)
        {
            log.InfoFormat("CommunicationException occured on product change notification: {0}.", ce.Message);
        }
        catch (ObjectDisposedException)
        {
            log.Info("Communication channel is disposed.");
        }
        catch (Exception e)
        {
            log.WarnFormat("Unhandled {0} on client callback: {1}", e.GetType(), e.Message);
        }

        SendProductChanged = false;
    }

The SendProductChanged = false; SendProductChanged = false; line will take care of unbinding the event handler. 行将解开事件处理程序的绑定。

You can write a wrapper method which takes Actions of Funcs as parameters and you can use try catch blocks inside this function. 您可以编写一个包装函数方法,该方法将Funcs的动作作为参数,并且可以在此函数内使用try catch块。 You can call your functions using this function; 您可以使用此函数来调用函数; something like: 就像是:

public void CallMethod(Action methodToBeCalled)
{
   try
   {
      methodToBeCalled();
   }
   catch 
   .....
   ....
}

Then call your functions like: 然后像下面这样调用您的函数:

CallMethod(() => client.OnProductChanged(products));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM