我编写了一个 PHPUnit 测试,用于检查在调用方法时是否从闭包中抛出异常。闭包函数作为参数传入方法,并从中抛出异常。
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;
}
}
在ExternalResourceTemplate上指定的get函数的代码是
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
}
}
知道为什么调用 fail assert 语句吗?在 PHP 中,您不能捕获闭包抛出的异常吗?或者是否有一种我不知道的处理它们的特定方法。
对我来说,异常应该只是传播出返回堆栈,但它似乎没有。这是一个错误吗?仅供引用,我正在运行 PHP 5.3.3
最佳答案
感谢您的回答...
设法找出问题所在。看起来问题在于被调用的 try-catch block 是调用闭包的 block 。这是有道理的...
所以上面的代码应该是
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");
}
}
所以看起来 PHP 5.3.3 在提到的所有问题之后都没有错误。我的错。
关于php - 为什么我从闭包中抛出的异常没有被捕获?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17230637/