Fault Contract in WCF - WCF Service Tutorial

In this article, we will see how to implement Fault Contract in WCF.
In typical ASP.Net code we use try catch block to manage exception, but in WCF Fault Contract is used handle exception so that reason of error can reach to the client.

WCF Fault Contract

If you are new to WCF Contracts, please read my earlier blog for here. WCF has provided a way to handle error/exception using Fault Contract.

In WCF, exception message does not reach to the client, it is difficult for the client to analyze the issue/error. By default, a generic error message is sent to the client due to security reason.

In this case, it becomes difficult for the client to understand the exception message. Fault Contract in WCF is used to solve this.
If you have created a WCF project and an exception occurs while consuming it via a client, then in general case a common exception message is received by the client.

Such common exception messages may confuse us to exactly identify the issue at client level.

The right exception message has many benefits, such as the user knows what the issue has come up with and also the developer has ease in tracing the issue so that it can be resolved.



How to implement Fault Contract in WCF?

In Fault Contract, an exception caught at service end and thrown at the client end.
To overcome this type of problem, we use fault contract in WCF.
To understand the fault contract in WCF better, let's try to implement it.

Below is a service class in WCF.

[ServiceContract]

    public interface IService1

    {

        [OperationContract]

        [FaultContract(typeof(WCFEXception))]

        int GetResult(int value1, int value2);

        

        // TODO: Add your service operations here

    }


    [DataContract]

    public class WCFEXception

    {

       [DataMember]

        public string Reason { getset; }

        


    }


Create a client to consume and see the error details.

static void Main(string[] args)

        {

            try

            {

                Service1Client obj = new Service1Client();

                int result = obj.GetResult(10, 0);

            }


            catch(FaultException<WCFEXception> ex)

            {

                Console.WriteLine(ex.Reason);

            }


        }


This time you will get the exact exception message that the WCF service has sent, this is because we have implemented fault exception in our code.

Hope you like this article.

Comments