ramlicious Blogs by Tina & Prabhu

December 2, 2011

Exception handling in WCF Services using SOAP Faults

Filed under: .NET,C#,Programming,WCF — Prabhuram @ 3:07 pm

One way I handle exceptions between WCF services and the service client proxy class is using the SOAP Faults. All you do is:

  1. Introduce <serviceDebug> attribute in the serviceBehavior\behavior element with includeExceptionDetailInFaults=”Boolean”
  2. Introduce a DataContract class that can take the properties that you wanted to pass to the proxy client.
  3. Decorate the OperationContract method with another attribute called FaultContract.
  4. Throw the FaultException from with the OperationContract.
The change in the service’s web.config will be
  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <serviceMetadata httpGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="true"  />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>

and the exception carrier will be something like this.

    [DataContract]
    public class MyException
    {
        [DataMember]
        public string ErrorMessage { get; set; }

        public MyException()
        {

        }

        public JsfException(string message)
        {
            this.ErrorMessage = message;
        }
    }

and service’s operation contract is decorated with FaultContract.

    [ServiceContract]
    public partial class MyServices
    {

        [OperationContract]
        [FaultContract(typeof(MyException))]
        public int Exec(int something)
        {
            // Do something
        }
    }

and now you will throw the exception like this.

    [ServiceContract]
    public partial class MyServices
    {

        [OperationContract]
        [FaultContract(typeof(MyException))]
        public int Exec(int something)
        {
            try
            {
                // Do something
            }
            catch (Exception ex)
            {
                MyException errMsg = new MyException(ex.Message) { Source = ex.Source };
                throw new FaultException<MyException>(errMsg, new FaultReason(errMsg.ErrorMessage), new FaultCode("MyCode"));
            }
        }
    }

and you can simply use this from the client like this.

        try
        {
            // Do something
        }
        catch (FaultException<MyException> ex)
        {
        }

No Comments

No comments yet.

RSS feed for comments on this post.

Sorry, the comment form is closed at this time.

Powered by WordPress