If any exception got in the WCF service method, by default it will converted to the FaultedException. So WCF client is unable to find the what exactly Exception raised at the service method. To send exception details from WCF service method to the client we can do this in several methods. One method is sharing here.
Pre Implementaion :
Before implementation we have to decide, what we need to send to the client complete exception details or some custom message with some reference id for the further reference and log exception at service level. This would be completely based on the requirement.
Implementation :
It is the four steps process
1)for the implementation of the we need to create one class ( Shared Contract). This class should have properties to hold and sending exception details to the WCF client as belowusing
System.Runtime.Serialization; //This class should be DataContract [DataContract] public class MyFaultException { [DataMember] //Data members should be according to the requirement, this values can send to WCF client public Exception FaultDetailProperty1 { set; get; } [DataMember] public string FaultDetailProperty2 { set; get; } }
2)The OperationContract of service method(s) which we need to handle exception and send exception details to the client we need to add FaultContract details as below,
[OperationContract] [FaultContract(typeof(MyFaultException))] // MyFaultException is the class created in the step 1 string MyServiceMethod(int id);
3) Exception handling at the WCF service
[OperationBehavior] public string MyServiceMethod(int id) { try { //Service method implementation } catch (Exception ex) // Here type of the exception type would be based on the requirement { //This is the class we have created in the step 1 MyFaultException myFaultExceptionObj = new MyFaultException(){ Exception = ex, Message = "No product" }; // Throwing the exception throw new FaultException( myFaultExceptionObj, "Some message here..."); //Here if we throw ex directly( ie., throw ex;) //then by default it will converted to FaultedException and client can not able to find what exception is exactly } }
4) Exception handling at WCF client
try
{ var myServiceClient = new MyServiceClient(_myServiceEndpointName) String serviceMessage = myServiceClient.MyServiceMethod(productId); } catch (FaultException ex) //Checking for the handled exception from the service { Object errorDetails = ex.Detail.FaultDetailProperty1; // we can access all properties of MyFaultException object using : ex.Detail } catch (Exception ex) //Checking for unhandled exceptions { //handle unhandled service exceptions }