Why is my exception thrown from a closure not caught?

I wrote a PHPUnit test that checks to see if an exception is thrown when closing a method call. The close function is passed as an argument to the method with an exception to it.

public function testExceptionThrownFromClosure() { try { $this->_externalResourceTemplate->get( $this->_expectedUrl, $this->_paramsOne, function ($anything) { throw new Some_Exception('message'); } ); $this->fail("Expected exception has not been found"); } catch (Some_Exception $e) { var_dump($e->getMessage()); die; } } 

The code for the get function specified on the ExternalResourceTemplate,

 public function get($url, $params, $closure) { try { $this->_getHttpClient()->setUri($url); foreach ($params as $key => $value) { $this->_getHttpClient()->setParameterGet($key, $value); } $response = $this->_getHttpClient()->request(); return $closure($response->getBody()); } catch (Exception $e) { //Log //Monitor } } 

Any ideas why the fail assert statement is being called? Can you not catch the exceptions thrown from closures in PHP, or is there a specific way to deal with them that I don’t know about.

For me, the exception should just propagate the original stack, but it does not appear. This is mistake? FYI I am running PHP 5.3.3

+6
source share
2 answers

Thanks for answers...

I managed to solve the problem. It seems that the problem is that the calling block that is being called is the one in which the closure is being called. What makes sense ...

So the code above should be

 public function get($url, $params, $closure) { try { $this->_getHttpClient()->setUri($url); foreach ($params as $key => $value) { $this->_getHttpClient()->setParameterGet($key, $value); } $response = $this->_getHttpClient()->request(); return $closure($response->getBody()); } catch (Exception $e) { //Log //Monitor throw new Some_Specific_Exception("Exception is actually caught here"); } } 

So, it looks like PHP 5.3.3 does not have an error after everything that has been mentioned. My mistake.

+2
source

I can not reproduce the behavior, my example script

 <?php class Some_Exception extends Exception { } echo 'php ', phpversion(), "\n"; $foo = new Foo; $foo->testExceptionThrownFromClosure(); class Foo { public function __construct() { $this->_externalResourceTemplate = new Bar(); $this->_expectedUrl = '_expectedUrl'; $this->_paramsOne = '_paramsOne'; } public function testExceptionThrownFromClosure() { try { $this->_externalResourceTemplate->get( $this->_expectedUrl, $this->_paramsOne, function ($anything) { throw new Some_Exception('message'); } ); $this->fail("Expected exception has not been found"); } catch (Some_Exception $e) { var_dump('my exception handler', $e->getMessage()); die; } } } class Bar { public function get($url, $p, $fn) { $fn(1); } } 

prints

 php 5.4.7 string(20) "my exception handler" string(7) "message" 

as was expected

0
source

Source: https://habr.com/ru/post/947815/


All Articles