How to: Throw Exceptions from a Web Service Created Using ASP.NET

[Note: This topic is pre-release documentation and is subject to change in future releases. Blank topics are included as placeholders.]

Code Example

The following code example throws a SoapException and provides additional details about the exception by setting the Detail property. For more on throwing exceptions from ASP.NET Web services, see Handling and Throwing Exceptions in XML Web Services.

<%@ WebService Language="C#" class="ThrowSoapException"%>

using System;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Serialization;
using System.Xml;

public class ThrowSoapException : WebService 
    // This Web service method throws a SOAP client fault code.
    public void myThrow(){

        // Build the detail element of the SOAP fault.
        System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
        System.Xml.XmlNode node = doc.CreateNode(XmlNodeType.Element,
             SoapException.DetailElementName.Name,              SoapException.DetailElementName.Namespace);

        // 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.
        //Throw the exception    
        SoapException se = new SoapException("Fault occurred",
          Context.Request.Url.AbsoluteUri ,

        throw se;