Exceptions or Error codes

error handlingexceptionsprogramming practices

We are building a web service(SOAP, .Net) which would be talking to (mostly) native clients (windows, C++) and we are wondering what is the best way to communicate errors to the client (e.g. SomethingBadHappened like login service not available or something like user not found) and haven't been able to decide between throwing exception to the client or using some kind of error code model to do the above.

What you would prefer on the handling on the client side: receiving a error code or handling a ServerFault exception which contains the reason for the error?
1) Why are we thinking exception: Because it would make server side code a lot more uniform
2) Why are we thinking error codes: Because we think it makes more sense from the client side perspective.

If 2) is really true we would probably want to go for error codes than exceptions? Is that the case here?

Also, would the answer change if we were talking to managed clients instead of native clients?

Best Answer

SOAP has a concept of faults, you can convert an exception to a fault on the server side and on the client proxy the fault can again be converted back to an exception. This works remarkably well in WCF and Java metro stack, cannot comment on native C++ clients.

As regards to SOA best practice define one generic fault and few specific faults only if the client need to handle a certain type of error differently. Never send a exception stack trace to client in production deployment. This is because in theory the server trace has no meaning for the client and for security reasons as well. Log the full error and stacktrace on the server and send a unique reference to the log in the fault. In WCF I use the Microsoft Exception Handling block from Enterprise Library to generate a guid and also convert a exception to SOAP fault.

Check the guidance at Microsoft Patterns and Practices.