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.
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 { get; set; } } |
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.
- Introduction to WCF
- ABC of WCF
- Basics of WCF Architecture
- WCF vs Web Service
- What is XML serialization?
- WCF Binding
- Create first WCF application
- Fault Contract in WCF
- WCF Data Contract vs Message Contract
- Message Contract
- Data Contract Serialization and De-Serialization
- Data Contract in WCF
- Operation Contract in WCF
- Service Contract in WCF
- How to host a WCF service in IIS?
- WAS Hosting in WCF
- Self Hosting in WCF
- How to create WCF RESTful Service.