Chris Cooper Chris Cooper -4 years ago 59
C# Question

Throwing exceptions from .NET web service

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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download