8

我编写了一个 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
    }
}

任何想法为什么调用失败断言语句?你能不能捕捉到 PHP 中的闭包引发的异常,或者是否有一种我不知道的特定方法来处理它们。

对我来说,异常应该只是传播出返回堆栈,但它似乎没有。这是一个错误吗?仅供参考,我正在运行 PHP 5.3.3

4

2 回答 2

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 毕竟没有提到的错误。我的错。

于 2013-06-21T09:55:02.233 回答
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"

正如预期的那样

于 2013-06-21T08:40:34.320 回答