Connectionmanager connect在CakePHP 3中返回致命错误而不是重定向

Connectionmanager connect在CakePHP 3中返回致命错误而不是重定向,cakephp,cakephp-3.4,Cakephp,Cakephp 3.4,我在CakePHP3.4中工作 在我的组件中,我正在检查是否可以安装数据库连接。若无法建立数据库连接,请将用户重定向到安装插件以设置数据库配置 这就是我签入组件的方式 <?php namespace Installer\Controller\Component; use Cake\Controller\Component; use Cake\Controller\ComponentRegistry; use Cake\Datasource\ConnectionManager;

我在CakePHP3.4中工作

在我的组件中,我正在检查是否可以安装数据库连接。若无法建立数据库连接,请将用户重定向到安装插件以设置数据库配置

这就是我签入组件的方式

<?php
 namespace Installer\Controller\Component;

 use Cake\Controller\Component;
 use Cake\Controller\ComponentRegistry;
 use Cake\Datasource\ConnectionManager;
 use Cake\Core\Configure;
 use Cake\Filesystem\File;

 /**
  * Install component
  */
 class InstallComponent extends Component
 {
     public function installationCheck()
     {
         // connection to the database
         try {
             $db = ConnectionManager::get('default');

             if(!$db->connect()) {      // line 23
                return $this->redirect(['plugin' => 'Installer', 'controller' => 'Install', 'action' => 'index']);
             }
         } catch (Exception $e) {

         }


        return true;
     }
 }

如果检查ConnectionManager::get方法的定义,您将看到它要么返回连接对象,要么抛出MissingDatasourceConfigException。因此,您可能需要将代码包装在try-catch块中:-

public function installationCheck()
{
    try {
        $db = ConnectionManager::get('default');

        // connection to the database
        if (!$db->connect()) {
           return $this->redirect(['plugin' => 'Installer', 'controller' => 'Install', 'action' => 'index']);
        }
    } catch (\Exception $e) {
    }

    return true;
}

我在try-catch块中包含了代码,但try块中仍然存在错误。已更新的问题,更新的代码缺少use语句或前导斜杠表示异常。更好的方法是专门捕获\Cake\Datasource\Exception\MissingDatasourceConfigException和/或\Cake\Database\Exception\MissingConnectionException。感谢@ndm在异常中添加前导斜杠
public function installationCheck()
{
    try {
        $db = ConnectionManager::get('default');

        // connection to the database
        if (!$db->connect()) {
           return $this->redirect(['plugin' => 'Installer', 'controller' => 'Install', 'action' => 'index']);
        }
    } catch (\Exception $e) {
    }

    return true;
}