PHP SOAP 错误捕获

2022-08-30 15:56:09

我越来越绝望,我想要的只是简单的错误处理,当PHP SOAP Web服务关闭以回显错误消息登录服务关闭时。请帮帮我!

目前,它仍然显示错误(以及警告...):

Fatal error: SOAP-ERROR: Parsing WSDL

下面是脚本:

<?php
session_start(); 
$login="0000000000000nhfidsj"; //It is like this for testing, It will be changed to a GET

$username = substr($login,0,13); //as password is always 13 char long 
                                 //(the validation is done int he javascript)
$password = substr($login,13);
try 
{
    ini_set('default_socket_timeout', 5); //So time out is 5 seconds
    $client = new SoapClient("http://192.168.0.142:8080/services/Logon?wsdl"); //locally hosted

    $array = $client->login(array('username'=>$username,
                                   'password'=>$password));

    $result = $array->return;

}catch(SoapFault $client){
    $result = "0";
}

if($result == "true")//as this would be what the ws returns if login success 
{
    $_SESSION['user'] = $login;
    echo "00";
}
else
{
    echo "01 error: login failed";
}
?>

答案 1

2018年7月更新

如果你不关心获取 SoapFault 的详细信息,只想捕获来自 SoapClient 的任何错误,你可以在 PHP 7+ 中捕获“Throwable”。最初的问题是,SoapClient可以在抛出SoapFault之前“致命错误”,因此通过使用Spredable捕获错误和异常,您将拥有非常简单的错误处理,例如

try{
    soap connection...
}catch(Throwable $e){
    echo 'sorry... our service is down';
}

如果您需要专门捕获SoapFault,请尝试原始答案,这应该允许您抑制防止抛出SoapFault的致命错误

与旧版 PHP 相关的原始答案

SOAP可能会在内部调用本机php函数时出现致命错误,这会阻止抛出SoapFaults,因此我们需要记录并抑制这些本机错误。

首先,您需要打开异常处理:

try {
    $client = new SoapClient("http://192.168.0.142:8080/services/Logon?wsdl",array(
       'exceptions' => true,
    ));
} catch ( SoapFault $e ) { // Do NOT try and catch "Exception" here
    echo 'sorry... our service is down';
}

然后,您还需要使用自定义错误处理程序静默地抑制源自 SOAP 的任何“PHP 错误”:

set_error_handler('handlePhpErrors');
function handlePhpErrors($errno, $errmsg, $filename, $linenum, $vars) {
    if (stristr($errmsg, "SoapClient::SoapClient")) {
         error_log($errmsg); // silently log error
         return; // skip error handling
    }
}

然后,您现在会发现它转为 SoapFault 异常,并显示正确的消息“Soap 错误:SOAP 错误:解析 WSDL:无法从 '...' 加载”因此,您最终返回到能够更有效地处理错误的 catch 语句中。


答案 2

Fatal error: SOAP-ERROR: Parsing WSDL意味着 WSDL 是错误的,也许是缺失的?所以它与肥皂无关。并且您无法通过尝试捕获来处理致命错误。看到这个链接 : http://ru2.php.net/set_error_handler#35622

当您尝试在浏览器中访问 http://192.168.0.142:8080/services/Logon?wsdl 时,您会得到什么?

您可以检查 WSDL 是否像这样存在

$handle = curl_init($url);
curl_setopt($handle,  CURLOPT_RETURNTRANSFER, TRUE);

$response = curl_exec($handle);
$httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);
if($httpCode == 404) {
    /* You don't have a WSDL Service is down. exit the function */
}

curl_close($handle);

/* Do your stuff with SOAP here. */

推荐