Friday, July 27, 2012

Custom FaultException implementation example in WCF

Create a custom exception class with datacontract attribute
namespace ETG.Base.CRM.WCFService
{
[DataContract]
public class CRMException
{
[DataMember]
public string Reason { get; set; }
}
}
Now here we see how the custom class can be used to throw exception to client


public tbContact GetCustomer(long customerId)
{
tbContact cust = new tbContact();
cust.OrgName = "ETG Consultancy";
try
{
using (ClientDTO cdto = new ClientDTO())
{
cust = cdto.GetContactInfoById(customerId);
}
}
catch (Exception ex)
{
CRMException crmexp = new CRMException();
crmexp.Reason = ex.ToString();
throw new FaultException(crmexp);

}
return cust;
}