Capturing SOAP faults and handling exceptions

15.7k views Asked by At

I am consuming a web services. Some methods throw exception when i invoked, because the parameters are invalid values, for example. I want to handle the exceptions but it don't contains any data information, only the message "Bad Request". This is my http response: enter image description here

        try
        {
            var data = client.SomeMethod(4);
        }
        catch (Exception exception)
        {
            // exception.Message = Bad Request
            // exception don't contains any more data information
        }   

How can I capture the other information

3

There are 3 answers

0
pepOS On BEST ANSWER

You can catch the exception with FaultException when the http status code is 2xx or 5xx, not 4xx. You can catch the http status code 4xx with System.ServiceModel.ProtocolException and then get the stream from the InnerException and parse it or get the FaultException from this stream. See http://blogs.msdn.com/b/nathana/archive/2011/03/31/deciphering-a-soap-fault-with-a-400-status-code.aspx for more details.

1
Bogdan On

I'm assuming this is a WCF web service? You are catching to wide of an exception. Try with a FaultException<TDetail>.

Typical deployed services use the FaultContractAttribute to formally specify all SOAP faults that a client can expect to receive in the normal course of an operation. Error information in a FaultContractAttribute appears as a FaultException (where the typeparameter is the serializable error object specified in the operation's FaultContractAttribute) when it arrives at a client application. The FaultContractAttribute can be used to specify SOAP faults for both two-way service methods and for asynchronous method pairs.

Because FaultException is both a FaultException and therefore a CommunicationException, to catch specified SOAP faults make sure you catch the FaultException types prior to the FaultException and CommunicationException types or handle the specified exceptions in one of those exception handlers.

1
Asiri Jayaweera On

You can use try-catch like below. Then you can access other information. You have to find the "TDetail". It provides by the web service.

catch(FaultException<TDetail> ex)
{
    ex.Code.ToString();
    ex.Reason.ToString();
}

Other way.

FaultException faultException = (FaultException)ex;
MessageFault msgFault = faultException.CreateMessageFault();
XmlElement elm = msgFault.GetDetail<XmlElement>();