Thursday, March 14, 2013

Fault contract in WCF

I have created one sample project and uploaded on goggle drive. To download click the below click then open the "File" option from the menu and then you will find the "Download" option.
WCFServiceUsingFaultContract Project

What is Fault Contract:

In simple WCF Service errors/Exceptions can be passed to the Client(WCF Service Consumer) by using 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.

Predicted: (Divide By Zero/Channel Exceptions/Application exceptions etc..)
using System;
 public void Divide(float number, float divideBy) 
       {
           If(dividBy ==0)
           {
             myServiceData.Result = false;
             myServiceData.ErrorMessage = "Invalid Operation.";
             myServiceData.ErrorDetails = "Can not divide by 0.";
             throw new FaultException(myServiceData);
           }
           return number/divideBy;
       }

UnPredicted: (which I explained in this article like connection failures/SQL Server down/Transport errors/Business logic errors.)
using System;
try
            {
                SqlConnection con = new SqlConnection(StrConnectionString);
                con.Open();
                myServiceData.Result = true;
             //Your logic to retrieve data & and return it. If any exception occur while opening the connection or any other unexpected exception occur it can be thrown to Client (WCF Consumer) by below catch blocks.
           }
            catch (SqlException sqlEx)
            {
                myServiceData.Result = true;
                myServiceData.ErrorMessage = "Connection can not open this " + 
                   "time either connection string is wrong or Sever is down. Try later";
                myServiceData.ErrorDetails = sqlEx.ToString();
                throw new FaultException(myServiceData, sqlEx.ToString());
            }
            catch (Exception ex)
            {
                myServiceData.Result = false;
                myServiceData.ErrorMessage = "unforeseen error occured. Please try later.";
                myServiceData.ErrorDetails = ex.ToString();
                throw new FaultException(myServiceData, ex.ToString());
            }

1 comment:

  1. Top 10 Casinos Near Harrah's Cherokee, NC - MapyRO
    Find the best Harrah's Cherokee Casinos and other Near Harrah's Cherokee in North 양주 출장안마 Carolina. Mapyro offers 구리 출장마사지 the best reviews 파주 출장안마 and 광주 출장샵 real 공주 출장마사지 guest reviews.

    ReplyDelete