rasmusx
rasmusx

Reputation: 905

PDO connection exception catching

I am having a difficult time with PDO. I extended PDO class and each time when there is a error making connection to database (with wrong password etc) it does not catch the exception.

Here is the current code:

public function __construct() {
    $dsn  = 'mysql:host=' . Config::host .
            ';dbname='    . Config::db;
    $user = Config::user;
    $pass = Config::pass;
    $opts = array(
        \PDO::ATTR_PERSISTENT => true,
        \PDO::ATTR_ERRMODE    => \PDO::ERRMODE_EXCEPTION 
    ); 

    try {
        parent::__construct($dsn, $user, $pass, $opts);
    } catch(PDOException $e) {
        echo $e->getMessage();
    }

}

Here is the shown error:

Fatal error: Uncaught exception 'PDOException' with message 
'SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost'
(using password: YES)' in
/home/rasmus/www/n1_cms/N1/Core/Database.php on line 21

PDOException: SQLSTATE[HY000] [1045] Access denied for user
'root'@'localhost' (using password: YES) in
/home/rasmus/www/n1_cms/N1/Core/Database.php on line 21

Edit: solution

Due to use of namespaces it did not work.

Changed:

catch(PDOException $e)

To:

catch(\PDOException $e)

Upvotes: 2

Views: 2814

Answers (2)

sikas
sikas

Reputation: 5523

Move the try/catch within parent::__construct($dsn, $user, $pass, $opts);

Upvotes: 0

Vitaly  Muminov
Vitaly Muminov

Reputation: 1952

seems that class 'PDOException' doesn't exist in your namespace. try to change the catch block: catch(\PDOException $e)

Upvotes: 2

Related Questions