duanboshe0001 2013-06-21 08:20
浏览 85
已采纳

为什么从闭包中抛出我的异常没被捕获?

I've written a PHPUnit test that checks if an exception is thrown from a closure when a method is invoked. The closure function is passed in as an argument to the method with an exception being thrown from 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 is

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 called? Can you not catch exceptions thrown from closures in PHP or is there a specific way of dealing with them I don't know about.

For me the exception should just propagate out the return stack, but it doesn't appear to. Is this a bug? FYI I'm running PHP 5.3.3

  • 写回答

2条回答 默认 最新

  • douchi0471 2013-06-21 09:55
    关注

    Thanks for the answers...

    Managed to figure out the issue. It looks like the problem is that the try-catch block that's being invoked is the one where the closure is invoked. Which 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 doesn't have a bug after all which was mentioned. My mistake.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥30 YOLO检测微调结果p为1
  • ¥20 求快手直播间榜单匿名采集ID用户名简单能学会的
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题