Monday, 28 December 2015

Fault Contract - Handling Errors in WCF service

What is FaultContract?


How do you handle errors in ASP.NET? It's very simple - just by adding the simple Try & Catch blocks. But when you come to WCF Service, if any unexpected error occurred (like SQL server down/Unavailability of data/Divide By Zero) in service, then error/Exception details can be passed to Client by using Fault Contract.

False Assumption

Most people think that we can't throw FaultException in catch block. It should be only based on some condition (if condition). But it is a false assumption. The main objective is, any type of exceptions(Predicted or Unpredicted) from service to be passed to Client (WCF Service consumer).

Using code:-



    [DataContract()]
    public class CustomError
    {
        [DataMember()]
        public string ErrorCode;
        [DataMember()]
        public string Title;
        [DataMember()]
        public string ErrorDetail;
    }

    [ServiceContract()]
    public interface IGreetingService
    {
        [OperationContract()]
        [FaultContract(typeof(CustomError))]
        string Greet(string userName);
    }

    public class GreetingService : IGreetingService
    {
        public string Greet(string userName)
        {
            // predicted Errors
            if (string.IsNullOrWhiteSpace(userName))
            {
                var exception = new CustomError()
                {
                    ErrorCode = "401",
                    Title = "Null or empty",
                    ErrorDetail = "Null or empty user name has been                                          provided"
                };
                throw new FaultException<CustomError>(exception, "Reason :                                                       Input error");
            }


            // Unpredictable Errors...
            try
            {
              SqlConnection con = new SqlConnection(StrConnectionString);
                con.Open();
                // some database operation code..
                con.Close();

            }
            catch (SqlException sqlEx)
            {
               var exception = new CustomError()
               {
                   ErrorCode = "402",
                   Title = "Null or empty",
                   ErrorDetail = "Connection can not open this " +
                                 "time either connection string is wrong                                     or Sever is down. Try later"
               };
               throw new FaultException<CustomError>(exception, "Reason :                                                       Server down");
            }
            catch (Exception ex)
            {
                var exception = new CustomError()
                {
                    ErrorCode = "403",
                    Title = "Null or empty",
                    ErrorDetail = "unforeseen error occurred. Please try                                      later."
                };
                throw new FaultException<CustomError>(exception, "Reason :                                                        Unforeseen Error");
              
            }


           // If there is no Error...
            return string.Format("Welcome {0}", userName);
        }
    }




In this post I explained how to handle exception at service side in WCF. I hope you enjoyed this post please comments your feed back and quires. Thank You.

No comments:

Post a Comment