views:

19

answers:

1

Hi, this might sound like a daft question but I can't seem to find a obvious answer. I have to quickly create a simple WCF service and I have created all the classes I need decorated with the DataContract and DataMember attributes and I have created a custom exception class and everything is working. However if an exception is thrown within my service no matter what it is should I always throw my FaultException<MyException> with a detailed message or use different exception types. I'm guessing I always throw that exception as the client can handle that single exception type.

Also if the client passes me a completely null object then I realise that is normal to throw an exception but what if a member of that class is not as expected such as null or even an empty string? Would I still throw my exception with that as the reason or would I just return a message in my response object? I know this might sound like a stupid question but just concerned that I might use exceptions to drive the functionality but then I'm thinking that throwing an exeption makes sense.

Many Thanks

Paul

+2  A: 

WCF supports "two types" of exceptions. First is unexpected exception - every common .NET exception thrown from your code, every unhandled exception and every non generic FaultException is handled as unexpected exception. Unexpected exception is SOAP:Fault which is not described in WSDL. Unexpected exception faults the channel.

Second type are expected exceptions. Expected exceptions are defined as FaultContracts. You throw expected exception by trhowing generic FaultException. Expected exceptions are described in WSDL as wsdl:fault messages for operations. Fault contract is added as XSD type for expected exception. Because of this client can parse Detail of SOAP:Fault and provide it as strongly typed object. You can provide some information about exception in fault contract - it is just on you what information do you provide to a client.

When you code your service you have to differ what is expected exception and what is not. For example when you create operation GetDataById expected exception is DataNotFound or IncorrectIdFormat, etc. So data validation is expected exception and you can say your user what field had incorrect value. You can also have some general expected exception to wrap other unexpected problems - this exception should be usually used in IErrorHandler implementation as global exception handler. If you don't use global exception handler you should not deal with unexpected exceptions.

Ladislav Mrnka
Many thanks for your response. I've implemented an IErrorHandler and it is making sense now.
Paulie Waulie