I have created a WCF service and client and it all works until it comes to catching errors. Specifically I am trying to catch the EndpointNotFoundException
for when the server happens not to be there for whatever reason. I have tried a simple try/catch block to catch the specific error and the communication exception it derives from, and I've tried catching just Exception. None of these succeed in catching the exception, however I do get
A first chance exception of type 'System.ServiceModel.EndpointNotFoundException' occurred in System.ServiceModel.dll
in the output window when the client tries to open the service. Any ideas as to what I'm doing wrong?
I was able to replicate your issue and got interested (since I needed the same). I even researched a way to handle \ catch first chance exceptions but unfortunately it is not possible (for managed code) for .net framework 3.5 and below.
On my case I always get a
System.ServiceModel.CommunicationObjectFaultedException
whenever something gets wrong on the service or whenever I access a down service. It turns out that c#'susing
statement is the cause since behind the scene, theusing
statement always closes the service client instance even if an exception was already encountered (it doesn't jump to catch statement directly).What happens is that the original exception
System.ServiceModel.EndpointNotFoundException
will be replaced by the new exceptionSystem.ServiceModel.CommunicationObjectFaultedException
whenever theusing
tries to close the service client instance.The solution i've made is to not use the
using
statement so that whenever an exception is encountered inside the try block it will instantly throw the exception to the catch blocks.Try to code something like:
Instead of:
And you'll be able to catch the right exception then.
Take a look at this post for details on this possible solution. The code shows use of a generate proxy but is valid on ChannelFactory and others as well.
Typical here-be-dragons pattern
Proper pattern:
Or, as expressed in your question without a using statement,
This may be a reporting issue for the debugger, rather than not actually catching the exception. this post gives some tips on resolving it, if that is the case... Why is .NET exception not caught by try/catch block?
Place a try catch block in the CompletedMethod.
An Example:
What is a First Chance Exception?