Catching SoapClient Errors

Posted by Nessa | Posted in , | Posted on February 1, 2011

0

I recently wrote a PHP script that uses SoapClient to connect to a SOAP server to verify username/password credentials for a monitoring system.  The script basically returns the result as a yes or no – however, as we all know with SOAP, when you hit an error you get a mess of crap that comes back like this:

Uncaught SoapFault exception: [ERROR_BAD_LOGIN] Bad login or password. in /path/to/stuff.php:20

Stack trace:
#0 [internal function]: SoapClient->__call('GetAccountByNam...', Array)
#1 /path/to/stuff(20): Utils_SoapClient->GetAccountByName(Object(SoapVar))
#2 {main}

All I need is an error code, and when the SOAP function fails (which is expected if the login credentials are invalid), the script halts and I don’t get anything.  Luckily, PHP has pretty good exception handling that can tell SOAP to treat output like a test.   For example, the following line of code in the above example passes a username string ($struct) to a SOAP object, and is the line of code that is failing:

$result=$accountService->GetAccountByName(new SoapVar($struct, SOAP_ENC_OBJECT));
$result_username = $result->UserAccount->AccountId;

In my case, if the login credentials being tested are incorrect, the value of the $result variable should be empty.  To suppress the ugly SOAP error and only return what I want, I use exceptions:

>try {
$result=$accountService->GetAccountByName(new SoapVar($struct, SOAP_ENC_OBJECT));
}
catch(SoapFault $result){
}
catch(Exception $result){
}

Therefore, I can now use the value of $result as intended:

if(!empty($result_username)){
 
echo "Login OK";
exit(0);
}else{
</code>
<code>echo "Login failed";
exit(1);
}
Be Sociable, Share!

Post a comment