Friday, December 21, 2007

Custom Soap Fault

Here's some code to Build a custom soap exception so you don't return a standard Exception from a web service. I'm sure there are better ways to do this these days, but I've been using this for 4 years.

#region BuildSoapFault
/// Build a custom soap error message

/// The string to add to the message
/// A Soap Exception
private SoapException BuildSoapFault(string message)
// Build the detail element of the SOAP fault.
System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
System.Xml.XmlNode node = doc.CreateNode(XmlNodeType.Element,
// Build specific details for the SoapException.
// Add first child of detail XML element.
System.Xml.XmlNode details =
doc.CreateNode(XmlNodeType.Element, "mySpecialInfo1",
System.Xml.XmlNode detailsChild =
doc.CreateNode(XmlNodeType.Element, "childOfSpecialInfo",
// Add second child of detail XML element with an attribute.
System.Xml.XmlNode details2 = doc.CreateNode(XmlNodeType.Element, "mySpecialInfo2",
XmlAttribute attr = doc.CreateAttribute("t", "attrName",
attr.Value = "attrValue";
// Append the two child elements to the detail node.
SoapException se = new SoapException(message,
Context.Request.Url.AbsoluteUri ,
return se;

No comments: