Tag Archives: WCF

Fault handling in WCF services

It is oprobably very well known to most WCF developers, but there is a methodology previously unknown to me for handling exceptions in a WCF service, and handling them gracefully.  Hopefully this post will give enough of an overview to the required steps to communicate fault conditions to the client to allow you to handle them in your code.

There are a few steps required in order to create the fault data, but they are all quite simple.

First, you need to create a DataContract object to hold the fault details.  Mine looks like this.

using System;
using System.Runtime.Serialization;
 
namespace MyOrganisation.MyService
{
    [DataContract(Namespace = "http://schemas.MyOrganisation.com/CentreService/2008/08")]
    public class UnexpectedServiceFault
    {
        private int errorCode = -1;
        private string errorMessage = "UNDEFINED";
        private string additionalData = String.Empty;
 
        [DataMember]
        public int ErrorCode
        {
            get { return errorCode; }
            set { errorCode = value; }
        }
 
        [DataMember]
        public string ErrorMessage
        {
            get { return errorMessage; }
            set { errorMessage = value; }
        }
 
        [DataMember]
        public string AdditionalData
        {
            get { return additionalData; }
            set { additionalData = value; }
        }
    }
}

That’s the object that will hold the data for presentation to the client. Now we’ll examine how to use it.

In the interface for your service class, you’ll need to decorate the methods for which you wish to provide fault handling. This is a simple case of adding the following line to the code.

[FaultContract(typeof(UnexpectedServiceFault))]

so, and example method signature would look like this.

/// <summary>
/// A dummy method to demonstrate fault handling
/// </summary>
/// <param name="aParam">A parameter to the method</param>
[FaultContract(typeof(UnexpectedServiceFault))]
[OperationContract]
void MyMethod(string aParam);

This tells the compiler to generate the WSDDL required to support fault handling for this method. Now, we need to implement this in the actual service code.

/// <summary>
/// A dummy method to demonstrate fault handling
/// </summary>
/// <param name="aParam">A parameter to the method</param>
[FaultContract(typeof(UnexpectedServiceFault))]
[OperationContract]
void MyMethod(string aParam);

This tells the compiler to generate the WSDDL required to support fault handling for this method. Now, we need to implement this in the actual service code.

/// <summary>
/// A dummy method to demonstrate fault handling
/// </summary>
/// <param name="aParam">A parameter to the method</param>
[FaultContract(typeof(UnexpectedServiceFault))]
[OperationContract]
public void MyMethod(string aParam)
{
  try
  {
    
  }
  catch(Exception ex)
  {
    UnexpectedServiceFault fault = new UnexpectedServiceFault();
    fault.ErrorMessage = ex.Message;
    fault.ErrorCode = 101;  // an error code to identify the fault location
    fault.AdditionalData = ex.StackTrace;
    FaultException<UnexpectedServiceFault> faultException = new FaultException<UnexpectedServiceFault>(fault);
    throw faultException;
  }
}

So, in the catch block, we created a new object of type UnexpectedServiceFault (as we defined in the first step), populated it’s data, and then wrapped it in the FaultException type provided by System.ServiceModel. It is this FaultException that we throw to the client.

In order to enable passing the fault data back to the client, we need to configure the host (in my case IIS) to pass exception details back to the caller. In my web config, I created a new ServiceBehaviour element containing a serviceDebug element. I then set the value of IncludeExceptionDetailsInFaults to true, and associated the behaviour with the service.

<?xml version="1.0"?>

<configuration>
  <system.serviceModel>
    <services>
      <service name="MyOrganisation.MyService" 
           behaviorConfiguration="MyServiceBehaviour">
        <endpoint contract="MyOrganisation.MyService" binding="wsHttpBinding"/>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="MyServiceBehaviour" >
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug httpHelpPageEnabled="true" includeExceptionDetailInFaults="true" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>

Now all that remains is to implement the handling at the client. Once you’ve updated the service reference information, you can catch excpetions of type System.ServiceModel.FaultException and handle them as required. In a simple case like so :

catch(FaultException<UnexpectedServiceFault> ex)
{
  Console.WriteLine("An error occurred :: " + ex.Detail.ErrorMessage);
}

Quite a simple process, but it can be a bit fiddly. If you have problems, I’d suggest going back and re-checking each step of this guide. I’m going to do the same in the next day or two, just to make sure I haven’t missed anything. :)

WCF Services – a compatibility hack

I’ve recently had to start developing a set of WCF services for my company to use.  All good stuff, you might say – and tyou’d be right.  For the most part.

The area in which things get “interesting” is around the requirement for backwards-compatibility with some existing .Net 1.1 applications that consume traditional web services.  These applications are horrendously complex, and the fewer changes to the code base we have to make, the better.  With this in mind, we created the WCF services to mirror the old web services as closely as possible and that’s where the fun began.

The issue that set me on a journey of discovery and hackery was around a method that returned a simple boolean type.

public bool NameIsInList(string name)

{

// implementation

return true;

}

Nothing fancy there.  However, exposing the service using basicHttpBinding had an unfortunate side effect.  The method signature was refactored to :

public void NameIsInList(string name, out bool NameIsInListResult, out bool NameIsInListResultSpecified);

Less than ideal.

No matter what I tried (including contacting Amit) I couldn’t make the down-level compatible web service return a simple boolean result.  Given how much effort we would have to go to to update the calling methods in the legacy systems, I had to find another way forward.

In the end, the solution was extremely simple, if a little hacky.  Create an ASMX web service that handled the calls to the WCF service, and presents the legacy apps with the data they expect.

[WebMethod]
public bool NameIsInList(string name)
{
using (MyWcfService.ServiceClient WcfClient = new MyWcfService.ServiceClient(“WSHttpBinding_MyService”))
{
return WcfClient.NameIsInList(name);
}
}

Not the prettiest solution, but it works.

There are a few extra benefits that I wasn’t expecting from this approach, too.  I’ll post about those tomorrow.