Fault Contract in WCF - WCF Service Tutorial

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 Fault Contract, an exception caught at service end and thrown at the client end. 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.

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.

If you write a service and consume it in a client. You will get below error message.
This is a general exception message and in this case, a developer gets confused about this exception message.


To make it more clear WCF Fault Contract can be used.

[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);
            }

        }


Now you should get error message thrown by WCF Service.

Comments

Popular

C# 6.0 New Features

SharePoint Interview Questions and Answers

Calling ASP.Net WebMethod using jQuery AJAX

What is Cloud Computing - A guide for beginners