警告:连接将被关闭,但有一个活动事务

Warning: The connection is going to be closed but there is an active transaction

我的控制器代码结构如下:

$connection = ConnectionManager::get('default');
$connection->begin();

try {
   //Some logic here to create entities, validate and save them
   //This code can throw exceptions

   $connection->commit();
}
catch (Exception $e) {
   $connection->rollback();
}

这是在 CakePHP 中使用事务的正确方法吗?如果确实抛出异常,则事务正确回滚,但出现警告:

Warning: The connection is going to be closed but there is an active transaction.

我想,我在某个地方漏掉了一个重要的点,因为我不明白为什么会发出这个警告。我一直认为,commit()rollback() 都会关闭交易。我错了吗?

好的,所以我从 2 或 3 个月以来一直试图找到这个问题的原因,就在我提出这个问题之后,我找到了! 各位,这就是 Whosebug 的魔法。

我的异常从未被捕获,因为我错过了 catch 指令中的 \。由于我的代码位于控制器中,因此 PHP 假定只捕获 App\Controller\Exception (默认控制器名称空间)。要捕获所有异常,代码必须是

catch (\Exception $e) {

简单。