Jul 9, 2007

WCF error practices / Faults

I recently gave a half-day training for a group of Windows embedded developers and decided to talk about error handling practices in WCF services (beside the mandatory topics of Architecture, Contracts, Bindings, Hosting, Security and Versioning).

First of all, the contract needs to be decorated with a FaultContract definition to prepare clients about what to expect concerning SOAP exceptions (faults):

[ServiceContract(Namespace="http://www.mleder.blogspot.com/EES/WME/Camp2007/06/20")]

public interface IWmeService

{

    [OperationContract]

    [FaultContract(typeof(WmeFault))]

    WmeRes SayHello(WmeRequest req);

}


WmeFault is a simple custom DataContract class of ours

[DataContract]

public class WmeFault

{

    private string why;

    [DataMember]

    public string Why

    {

        get { return why; }

        set { why = value; }

    }

 

    public WmeFault(string why)

    {

        this.Why = why;

    }

}


In the service implementation you just throw an exception with this type

public class WmeService : IWmeService

{

    public WmeRes SayHello(WmeRequest req)

    {

        if (req.Text.Contains("Markus"))

        {

            throw new FaultException<WmeFault>(new WmeFault("no, Markus"));

            // throw new FaultException("no, Markus");

        }

 

        WmeRes wmeRes = new WmeRes();

        return wmeRes;

    }

}


And on the client side we catch our nicely-modeled SOAP fault message as we always do with regular System.Exception.

try

{

    WmeRequest req = new WmeRequest();

    req.Text = text;

    wmeService.SayHello(req);

}

catch (FaultException<WmeFault> fex)

{

    Console.WriteLine("Client fault FaultException<WmeFault> : " + fex.Detail.Why);

}

No comments:

Post a Comment