我编写了一个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
答案 0 :(得分:2)
感谢您的回答......
管理以找出问题所在。看起来问题是被调用的try-catch块是调用闭包的块。这是有道理的......
所以上面的代码应该是
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在提到的所有内容之后都没有错误。我的错误。
答案 1 :(得分:0)
我无法重现行为,我的示例脚本
<?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);
}
}
打印
php 5.4.7
string(20) "my exception handler"
string(7) "message"
按预期