How to handle SoapClient Fault In PHP

3.3k Views Asked by At

I am calling a third party web service to get the user detail by the supplied credential. Below is my Soap Client Request.

$client = new \SoapClient($url, array("exception" => 0));        
$auth = '
<wsse:Security SOAP-ENV:mustUnderstand="1" xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
<wsse:UsernameToken>
<wsse:Username>' . $userName . '</wsse:Username>
<wsse:Password>' . $password . '</wsse:Password>
</wsse:UsernameToken>
</wsse:Security>';
$authvalues = new \SoapVar($auth, XSD_ANYXML);
$header1 = new \SoapHeader("http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd", "Security", $authvalues, true);   
$header2 = new \SoapHeader("http://xmlns.myweb.com/FulfillProductRequest/V1", "v1");    
$header3 = new \SoapHeader("http://xmlns.myweb.com/ParameterType/V2", "v2");    
$header4 = new \SoapHeader("http://xmlns.myweb.com/RequestHeader/V3", "v3");

$header = array();    
$header[] = $header1;    
$header[] = $header2;    
$header[] = $header3;    
$header[] = $header4;                
$client->__setSoapHeaders($header);    
$res = $client->FulfillProduct($FulfillProductRequest);    

When i am calling the WSDL,if i am getting the success response then there is no issue.

But if there is any error come in soapFault then my code shows fatal error.

Anybody have any idea how to handle the SoapFault plz share.

Thanks in anvance.

2

There are 2 best solutions below

7
On

You can try to wrap your $res = $client→FulfillProduct($FulfillProductRequest); in a try { } catch() {}.

For example:

try { 
  $res = $client→FulfillProduct($FulfillProductRequest);
} catch(Exception $e) {
  // An error has occured.
  // All information about the error has been stored in variable $e
  print_r($e);
}

Be aware, that you can set the SoapClient to never throw exceptions with your settings, so look into that first.

1
On

Maybe it will help someone.

$options =  ['trace'    => true,
            'debug'    => false,
            "exceptions" => true, 
            'version'  => SOAP_1_2,
            'connection_timeout' => 15];

$wsdl = "http://test.com?wsdl";

try {

    $soapClient=new SoapClient($wsdl,$options);

} catch (SoapFault $e) {

    logError($e->getMessage(),$e->getCode());
}