Why we need Fault Contracts in WCF? Why not just use error codes?

Technology CommunityCategory: WCFWhy we need Fault Contracts in WCF? Why not just use error codes?
VietMX Staff asked 3 years ago

Fault Contract is a way to handle an error/exception in WCF. In C# we can handle the error using try and catch blocks at the client side. The purpose of a Fault Contract is to handle an error by the service class and display in the client side.

  • We use return codes if it’s a known, possible error. If it’s a scenario that I know can, and will happen, then there’s a code that gets sent back.
  • Exceptions are used solely for things that I’m NOT expecting. This is why WCF’s architects chose to provide the Fault Contract mechanism, rather than implement the same functionality via return codes.

To support SOAP Faults, WCF provides the FaultException class. This class has two forms:

  • FaultException: to send an untyped fault back to the caller
  • FaultException: to send a typed fault data to the client. It is basically a Generic Type.
[OperationContract]
[FaultContract(typeof(MyException))]
string getDetails(int value);