dovhpmnm31216 2016-10-02 23:00
浏览 108
已采纳

PDO捕获PDOException错误

It works great if the connection is valid, but it seems PDOException doesn't actually work if the connection fails. The catch totally fails to execute. If its fails, it break execution of this line $this->dbh = new PDO("$db_driver:host=$db_host;dbname=$db_name", $db_user, $db_pass);. So i can't get PDOException in catch block. How do I keep get this to work?

<?php

namespace app\Helpers;

use \PDO;

/**
* Core class which exists only once through the application
*
*/
class Core
{
public $dbh; // handle of the db connexion
private static $instance;

// constructor to create a MySQLi instance (="MySQL Improved Extension")
private function __construct()
{

    $db_host = ConfigHelper::read('db.host');
    $db_name = ConfigHelper::read('db.basename');
    $db_user = ConfigHelper::read('db.user');
    $db_pass = ConfigHelper::read('db.password');
    $db_driver = ConfigHelper::read('db.driver');
    try {
        $this->dbh = new PDO("$db_driver:host=$db_host;dbname=$db_name", $db_user, $db_pass);
    } catch (PDOException $pdoex) {
        exit("Database connection failed: " . $pdoex->getMessage());
        return false;
    }

}
/**
 * get instance of Core object
 *
 * @return Object self
 */
public static function getInstance()
{
    if (!isset(self::$instance)) {
        $object = __CLASS__;
        self::$instance = new $object;
    }
    return self::$instance;
}

}

展开全部

  • 写回答

1条回答 默认 最新

  • doudi1978 2016-10-02 23:17
    关注

    It is a namespace issue.

    When within a namespace, you have to address every root level class name by prepending it with a backslash.

    But you didn't.

    But the worst part is that you should not catch a PDOException at all. Just leave it alone and let it report to a site-wide report handler

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部