5

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?

1
  • AFAIK, there should be no need to re-throw as you can configure faults to be sent down the wire. And on the face of it I would say yes, throw, but it depends - your framework might be structured to use composite types with Results and Errors collections, for instance. Commented Feb 9, 2011 at 9:36

3 Answers 3

5

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.

3

Using Exceptions vs custom error codes is always a hard decision. You should estimate, how 'exceptional' the case is and how do you plan to handle the error on the consumer side. Use exception is normally unexpected cases (like an important parameter is missing) and custom error codes to handle bussiness-like errors.

UPDATE: this of course only applies, if you are creating a new service. If you modify an existing one, you have to know how the existing clients use it and how they expect error codes.

3

Here is a nice article about web service exceptions

Not the answer you're looking for? Browse other questions tagged or ask your own question.