Tuesday, June 5, 2012

WCF converting exceptions to faults


To return all errors (dev) without any configurations:
<serviceBehaviors>
  <behavior name="Debug">
    <serviceDebug includeExceptionDetailInFaults="true" />
  </behavior>
</serviceBehaviors>

WCF   converting exceptions to faults
1)Create basic class
[DataContract]
    public class BlahServiceFault
    {
        [DataMember]
        public string Message { get; set; }

        [DataMember]
        public Guid Id { get; set; }
    }

2)Add reference to Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.WCF, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling

3)Add to interface
[OperationContract]
        [FaultContract(typeof(BlahServiceFault))]
        IEnumerable<blases> GetUserBlases();

4)add to service config file
<exceptionHandling>
    <exceptionPolicies>
      <add name="WCF Exception Shielding">
        <exceptionTypes>
          <add name="All Exceptions" type="System.Exception, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" postHandlingAction="ThrowNewException">
            <exceptionHandlers>
              <add type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.WCF.FaultContractExceptionHandler, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.WCF, Version=5.0.505.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" exceptionMessage="An error occured while processing the request." faultContractType=" BlahServiceFault" name="Fault Contract Exception Handler">
                <mappings>
                  <add source="{Message}" name="Message" />
                  <add source="{Guid}" name="Id" />
                </mappings>
              </add>
            </exceptionHandlers>
          </add>
        </exceptionTypes>
      </add>
    </exceptionPolicies>
  </exceptionHandling>


5)Usage in client
try
           {
               url = client.GetUserBlases(Params);
           }
           catch (FaultException<BlahServiceFault> ex)
           {
               lblError.Text = ex.Detail.Message;
           }

No comments:

Post a Comment