0
  1. Is it possible to catch all WCF statements in a single catch statement? - i.e on the code below i have 2 catches for WCF but my codes reaction to both is the same so i dont want to duplicate code
  2. Will both WCF catches, catch ALL WCF errors or am i missing any ?

Note i have seen these list here

try
       {
        // Some code......
       }
       catch (CommunicationException exception) // WCF Exception 
            {

            }

      catch (TimeoutException exception) // WCF Exception - 
            {

            }

      catch (Exception ex)
            {
                // Standard exception
            }
Community
  • 1
  • 1
user1438082
  • 2,740
  • 10
  • 48
  • 82

1 Answers1

2

In a WCF Client, you can capture exceptions thrown from a service catching a FaultException. You can also catch any other class of error if you want special handling (i.e., TimeoutException or CommunicationException).

Here's an example:

proxy ServiceClient();
try
{
    proxy = new ServiceClient();
    proxy.DoSomething();
}
catch (FaultException ex)
{
   // handle errors returned by WCF service
}
catch (CommunicationException ex)
{
  // handle communication errors here 
}
catch (TimeOutException ex)
{
  // handle timeouts here 
}
catch (Exception ex)
{
  // handle unaccounted for exception here 
}
finally
{
   if (proxy.State == CommunicationState.Opened)
   {
      proxy.Close();
   }
   else
   {
      proxy.Abort();
   }     
}
PeterB
  • 1,864
  • 1
  • 12
  • 9
  • 1
    I've updated to show other exceptions. CommunicationException and TimeoutException cover the WCF wire-level errors. – PeterB Apr 12 '14 at 12:49
  • 1
    Review the exception defined within the System.ServiceModel namespace. There are a bunch. See http://msdn.microsoft.com/en-us/library/System.ServiceModel(v=vs.110).aspx. Also, in your general Exception catch block, you can log the exception type as a way to discover any common exceptions for which you may need special error handling. – PeterB Apr 12 '14 at 14:04
  • as far as i can tell your list above catches all of them (especially CommunicationException cathes most exceptions) but i dont know and that link doesnt talk about that , i dont see the point in listing all failure modes if i can cover them under 3 as for me the action to take is the same for all failure modes from WCF. – user1438082 Apr 12 '14 at 14:10
  • 1
    It really comes down to what exceptions to you want to handle in a special way. You're right, just about all of the WCF exception derive from CommunicationException, so unless you want to take special action for something like ProtocolException, then you don't need to clutter up your code with all possible exceptions. – PeterB Apr 12 '14 at 14:26