Catching SoapClient Errors

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:

echo "Login OK";
<code>echo "Login failed";
Be Sociable, Share!

Leave a Reply

Your email address will not be published. Required fields are marked *