Monthly Archives: September 2008

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. :)

FIA strikes again

Once again, the FIA (Ferarri International Assistance) have shown the world where there true allegience lies.

At yesterday’s Belgian Grand Prix, the stewards decided to impose a 25 second penalty on Lewis Hamilton after ruling that he “gained an advantage by short-cutting the circuit.”

I was watching the race live, and saw the incident in question, and one thing I can tell you for certain is that Hamilton did indeed gain an advantage, but that he immediately backed off and returned the lead of the race to Raikkonen.  In fact, in order to pass him at the next corner, Hamilton went around the back of the Finn’s car in a perfectly legal manouvre.  I’m sure you can find the footage on YouTube by now to see for yourself.

What really get’s me wound up is the fact that Raikkonen managed to get in front of Hamilton again just a few laps later, and the win for Hamilton only came as a result of Raikkonen losibng control of his car on the wet track and spinning into the wall.  Hamilton can’t have gained that big an advantage then, can he?

So my message to the FIA is this.  This kind of activity is what we call “racing”.  This is different from the official view of motor racing, which in recent years seems to have been defined as ’20 cars driving in procession around a track for 90 minutes’.  Restricting the cars for the sake of it is not in the spirit of the sport.  Penalising drivers because they happen to not drive for Ferrari is not in the spirit of the sport.  Failing to apply rules on safety (Massa’s unsafe release from the pits in Spain) is not in the spirit of the sport.

It’s no wonder that so many people are giving up on the sport.  I am not going to continue to watch a corrupt sham, and I am not alone in that opinion.

note : all views expressed in this post are my personal opinion, and should not be miscontrued as fact.