如何在PHP中处理Soap客户端错误


How to handle SoapClient Fault In PHP

我正在调用第三方 Web 服务,以通过提供的凭据获取用户详细信息。以下是我的 Soap 客户端请求。

$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);    

当我调用WSDL时,如果我得到成功响应,则没有问题。

但是,如果肥皂故障中出现任何错误,那么我的代码将显示致命错误。

任何人都知道如何处理SoapFault,请分享。

谢谢。

您可以尝试将$res = $client→FulfillProduct($FulfillProductRequest);包装在try { } catch() {}中。

例如:

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);
}

请注意,您可以将SoapClient设置为永远不会在您的设置中引发异常,因此请先查看一下。

也许它会帮助某人。

$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());
}