Throwing exceptions from .NET web service

Chris Cooper picture Chris Cooper · Feb 9, 2011 · Viewed 17.6k times · Source

I have a set of web services generated using the [WebMethod] attribute. Is it considered "good practice" to throw ArgumentException from such a method if its arguments aren't properly specified (and no sensible defaults could be used)? If so, should this exception be caught and re-thrown in order to log it both on the server and the client?

Answer

StuartLC picture StuartLC · Feb 9, 2011

No, throwing exceptions from web services is not good practice, as .NET Exceptions (like ArgumentException) aren't supported cross platform (think of how a Java client would need to respond).

The standard mechanism for indicating exceptions in Web Services is a Soap Fault.

With .asmx, throwing a SOAPException will generate a fault for you.

If you move to WCF, you can look at FaultContracts.

For improved debugging of remote exceptions between a .Net client and .Net server, you could cheat and send an exception across the wire by using includeExceptionDetailInFaults in your config. The exception itself must be serializable in order for this to work. However, you will want to turn this off before your system reaches production.

As an aside, you will often find that if the caller's SOAP request call is too poorly formed (e.g. if your arguments include entities that can't be deserialized) that your WebMethod won't be called at all - the caller will just receive a fault (often quite cryptic).

The above faults raised for bad arguments from the client's call to your service should be generated when the call arguments are validated.

Possibly related - Once a request has passed validation, for your own internal system state assertion, you could also use Code Contracts to detect internal bugs (or possibly, missing validations which should have happened earlier). These however will not be propogated to the client.