views:

381

answers:

2

I am currently using a C# .NET Service in our client program. As part of the server design, several custom made exceptions are thrown to indicate specific errors (as in any normal desktop program).

The problem is that the Web Service catches these errors and serializes them into a FaultException, with the actual exception (like NoRoomsAvailableException) written in the Message field.

My question is whether there is a best practice for handling these errors. We have just begun working on this, and we would probably do some text pattern matching to pull out the exception type and error message, but it seems like a hacky way to do it, so any "clean" way of doing it would be much appreciated.

+1  A: 

The proper way would be to define fault contracts. For example in your web service you could do the following:

[DataContract]
public class NoRoomsAvailableFaultContract
{
    [DataMember]
    public string Message { get; set; }
}

Next you declare this contract for a given service operation

[ServiceContract]
public interface IMyServiceContract
{
    [OperationContract]
    [FaultContract(typeof(NoRoomsAvailableFaultContract))]
    void MyOperation();
}

And you implement it like so:

public class MyService : IMyServiceContract 
{
    public void MyOperation()
    {
        if (somethingWentWrong)
        {
            var faultContract = new NoRoomsAvailableFaultContract()
            {
                Message = "ERROR MESSAGE"
            };
            throw new FaultException<NoRoomsAvailableFaultContract>(faultContract);
        }
    }
}

In this case the NoRoomsAvailableFaultContract will be exposed in the WSDL and svcutil.exe could generate a proxy class. Then you could catch this exception:

try
{
    myServiceProxy.MyOperation();
}
catch (FaultException<NoRoomsAvailableFaultContract> ex)
{
    Console.WriteLine(ex.Message);
}
Darin Dimitrov
I assume this means that I can seperate FaultException<Type1> from FaultException<Type2> in my catch statements?
Christian P.
Yes you can catch different fault exceptions.
Darin Dimitrov
A: 

darin has the correct answer. I'll only say explicitly what he implies: web services do not pass exceptions. They return SOAP Faults. If you define your faults properly, as he does, then you get to throw FaultException<fault>. This will become a SOAP Fault with fault in the detail element. In the case of a .NET client, this will then be turned into a FaultException<fault>, which you can catch.

Other platforms may handle this somewhat differently. I've seen IBM's Rational Web Developer generate Java proxy code that creates a separate exception for each declared fault. That was a version before Java generics, so maybe by now it does the same thing as .NET does.

John Saunders