我快绝望了,我想要的只是当 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";
}
?>
最佳答案
2018 年 7 月更新
如果您不关心获取 SoapFault 详细信息而只想捕获来自 SoapClient 的任何错误,您可以在 PHP 7+ 中捕获“Throwable”。最初的问题是 SoapClient 在抛出 SoapFault 之前可以“ fatal error ”,因此通过使用 Throwable 捕获错误和异常,您将有非常简单的错误处理,例如
try{
soap connection...
}catch(Throwable $e){
echo 'sorry... our service is down';
}
如果您需要专门捕获 SoapFault,请尝试原始答案,它应该允许您抑制阻止 SoapFault 被抛出的 fatal error
与旧 PHP 版本相关的原始答案
SOAP 可以在内部调用 native php 函数时发生 fatal error ,这会阻止抛出 SoapFaults,因此我们需要记录并抑制这些 native 错误。
首先你需要开启异常处理:
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-ERROR:解析 WSDL:无法从‘...’加载”,因此您最终回到了 catch 语句能够更有效地处理错误。
关于PHP SOAP 错误捕获,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6952814/