Why we need Fault Contracts in WCF

675 views Asked by At

I have been getting my hands Dirty in WCF. Now one of the question which comes to my mind is regarding Fault Contracts in WCF.

I would like to know why we would be needing it. Consider a Sample Application where I am adding 2 Numbers.

So in the Response I have like 2 Fields

Result - Success/Error

Error - Error Details (Code + Text)

Now if my WCF service had any Exception I can catch it in the catch block and assign values to Response object

Result - Success/Error

Error - Error Details (Code + Text)

So where does Fault Contract come into the picture?

2

There are 2 answers

1
urig On

What you are doing in your example is you're indicating to the caller that an error has occurred via a "return code". Fault Contracts represent a different approach to doing this: exceptions.

There are many reasons why exceptions are considered better than return codes. Read this for example: Which, and why, do you prefer Exceptions or Return codes? . This is why WCF's architects chose to provide the Fault Contract mechanism, rather than implement the same functionality via return codes.

In your case the Fault Contract approach would mandate that you shouldn't return a response object. You should simply return an int. If anything exceptional happens that prevents you from returning the int, your code would throw a strongly typed Fault indicating to the caller what went wrong and how to, possibly, overcome it.

0
Wei Wei On

This is a old question, but I still wish to post some answers for future readers.

Found this website http://www.c-sharpcorner.com/UploadFile/aravindbenator/wcf-exception-handling-best-ways/.

The Author said, if we do not use Fault Contract, the response data (from service to client) will include some sensitive data.

If we do not have Fault Contract, in WCF app.config or web.config, and we still want Fault Exceptions or Web Fault Exceptions, we will set as: <serviceDebug includeExceptionDetailInFaults="true" />, however, if we set <serviceDebug includeExceptionDetailInFaults="false" />, we must have Fault Contract above service operations.