Today I would just like to show how to correctly write the code when using a WCF client proxy to call an WCF service.
Firstly you have to create a Service Reference to the service so that the relevant code is generated for the client proxy.
Here is the correct code:
Then I create a catch section to display the relevant details. In the code above I use Assert.Fail() because this code is used in a unit test, but you can but logging in or any other exception handling logic.
The finally section is there to check if the channel has closed successfully otherwise will call abort on the channel. This allows the correct exception details been catch if an exception is raised in the web method or when the channel is closed.
Here is the wrong code (The popular approach):
So what is wrong with this? Well the problem is that if an exception is raised in the web method UpdatePrice() and an exception is raised in the Close() method of the client proxy channel is closed by the using() statement then the close exception would hide the original exception that is raised by the web method UpdatePrice().
The first code snippet is much clearer and show what really is happening if an exception should be raised. Where the using does make the code smaller and handle the open closing of the client proxy, but could hide the specific details of the original exception.