Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP SoapFault not caught by exception handlers

Tags:

I am new to PHP exception handling and SOAP. For some reason I cannot catch a SoapFault. I don't know why. The soap server is not mine.

try { 
    $contact_id = $objSoapClient->getContactIdFromVisitorId('12345');
} 
catch (SoapFault $sf) { 
    echo "Soapfault"; 
} 
catch (Exception $e) { 
    echo "Exception"; 
}

I am purposely passing in the bad id 12345. When I enable errors I see the following message SoapFault exception: [SOAP-ENV:Client] Invalid Visitor ID. However, my catch SoapFault block nor my catch Exception block ever get hit. Why?

like image 859
mrtsherman Avatar asked Jun 16 '11 15:06

mrtsherman


2 Answers

The code you've submitted appears to be correct. Here's the only thing that comes to my mind.

With that said, if the code is located inside a class that define a namespace, you code will not work as it will try to reference Exception as \namespace\Exception which does not exist. "Passive" references such as those in catch clauses or instanceof expressions are permitted because the missing class could be loaded later.

For it to work, you have to prefix the class name with a slash (i.e. \Exception) to tell PHP to use PHP from the global space (or root if you want to call it that) (PHP) as opposed to your namespace;

<?php

namespace test;

class Foo
{
  public function bar()
  {
    try
    {
      something_that_might_break();
    }
    catch (\Exception $e)
    {
      // this will work
    }
  }
}

?>

You can find lots of information about namespaces here: http://php.net/manual/en/language.namespaces.php.

like image 75
Francois Deschenes Avatar answered Oct 03 '22 19:10

Francois Deschenes


The problem turned out to be my SoapClient declaration. There is an exceptions parameter that must be set in order for the exceptions to trigger.

$objSoapClient = new SoapClient('https://mywebservice.com/foo.wsdl', array(
    "trace" => false,  
    "exceptions" => true,     // <-------------- This!!!                                               
    'login' => 'username',    //username
    'password' => 'password', //password
    'features' => SOAP_SINGLE_ELEMENT_ARRAYS + SOAP_USE_XSI_ARRAY_TYPE 
));
like image 45
mrtsherman Avatar answered Oct 03 '22 18:10

mrtsherman