My web service method returns a collection object, this will serialize nicely, thanks to the way C# web services work!
But if my code throws an uncaught exception, I want to instead return a custom error object.
Is this possible using C# ASP.NET v2?
For example,
Normal Operation should return:
<Books>
<book>Sample</book>
<book>Sample</book>
</Books>
But on error I want
<error>
<errorMessage></errorMessage>
</error>
Yes, this is possible.
What you'll need to look into is the SoapException class, and specifically the Detail property of the SoapException class.
The SoapException class will effectively render a "Soap Fault", which is the standards-compliant mechanism for returning error information to clients/consumers from a web service method.
The "Detail" property of the SoapException class is of type XmlNode and can thus contain either a single node/element or a hierarchy of child nodes. The Detail node could therefore easily contain and act as the "parent" for the serialized representation of your own custom error object.
From MSDN:
Note that if you wish to remain correctly SOAP compliant with your web service responses, you'll need to return a SoapHeaderException rather than a SoapException if the error occurs within the client's header section of the original XML request (this can often be the case when using custom SOAP headers for e.g. security credentials) as detailed above.