简体   繁体   中英

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. 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. 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? 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?

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; 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. 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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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