Saturday, February 28, 2015

Raising SoapFaults on a Web Service

I have used SoapFaults (FaultExceptions) on Web Services before so here is  quick recap. In your Interface class add this declaration

[DataContract]
public class SPSoapFault
{
   public SPSoapFault(string errorMsg)
   {
       this.ErrorMsg = errorMsg;
   }
   [DataMember]
    public string ErrorMsg { get; set; }
}

Beneath the OperationContract declaration of the method you want to use this on addthe FaultContract attribute

[OperationContract]
[FaultContract(typeof(SPSoapFault))]

Now in the service you can throw FaultExceptions of this type

throw new FaultException<SPSoapFault>(new SPSoapFault("The byte array is null"), new FaultReason("Required parameter"));

Note that you must add a Fault Reason.

When calling this from a client application make sure you declare the faultexception that is in the web service references.

SPService.SPSoapFault spfault = new SPService.SPSoapFault();

the catch block of your try catch should include this

catch (FaultException<SPSoapFault> faultEx)
{

  spfault = faultEx.Detail;
 
string error = spfault.ErrorMsg;
  string reason = faultEx.Reason.ToString();
}

No comments: