Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 240
Chris Cooper Avatar asked Feb 09 '11 09:02

Chris Cooper


2 Answers

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.

like image 117
StuartLC Avatar answered Sep 17 '22 22:09

StuartLC


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.

like image 31
Dercsár Avatar answered Sep 21 '22 22:09

Dercsár