FaultContract is the word which came with WCF.As its name states it is for handling the faults.But how can we handle the fault? In this post I am just going to describe about implementing the FaultContract and its handling at client side.
What is FaultContract
It is just an attribute which is used to decorate the service method which is already marked as OperationContract.This tells that the method may throw the Fault using the specified generic class.Oh.What is this generic class? Just look at the code.
MyException is the generic class which I mentioned.Its just a class used to transmit the custom details about the fault to the client.
Dont forget to mark this class as DataContract.This class is normally known as ExceptionDetail or detailType in other sites and tutorials.
Invoking the Fault
In your service implementation you can have the try catch blocks and from the catch you can throw the FaultException.It will reach up to client and client can handle that.Also you can throw the Fault from anywhere in your code.
Even if you didn’t handle the exception it will reach to client if your web.config is proper.ie ServiceBehaviour is as follows
Lets see what are all the things we need to do at the server side.
- Create the class to transmit the exception details.
- Mark the service methods with FaultContract attribute by passing the detail class.
- Change your web.config to set includeExceptionDetails to true.
- Throw the FaultException from your service implementation from where ever required.
- Add the service reference.
- Wrap the service call with try catch and handle the FaultException.
You can download a sample from my sky drive which implements the above.