Earlier in my post, I discussed how you can structure WCF projects. Few things are still missing in that structure, especially Error Handling. With the current architecture, which is shown below, we can handle Errors and send meaningful information back to the Client. This is done using FaultExceptions.
Using FaultContracts is pretty easy. We specify what FaultContract each OperationContract is associated with. We don’t specify any fault if the OperationContract does not have any FaultContract.
And throw it when we want to:
The Client can catch this FaultException and get the ‘friendly’ exception messages:
Even though this seems to be a simple and easy method, it is not that efficient. Some of the problems or issues that we can highlight immediately reading the code above are:
1) There is no generic FaultContract, We need to specify a FaultContract for each of the OperationContract
2) As you can notice in the Client, we are explicitly catching the FaultException of our FaultContract type. This again can be different based on the FaultContract on that particular OperationContract
3) There isn’t a way where the errors are logged in the Service. It can be logged before throwing the FaultException, but again you have to do it each time you throw!
4) The Client has to anyhow catch other Exceptions that are not FaultExceptions!
So, do we have a good method where we can handle all the errors and send back meaningful messages back to the Client? Yes, we do!
I would go in detail about that in Part 2 🙂
You can download the Part 1 sample below: