We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Handling SQL Conecction error

How can i handle SQL connection if could not connect to database , for example : if the connection was not successfull throw a 500 error or forward to a controller.


$di = new FactoryDefault();
$cf = new Ini("../config/config.ini");

#   Database connection
$di['db'] = function() use ($cf) {
    return new DbAdapter([
        "host"      => $cf->database->host,
        "username"  => $cf->database->username,
        "password"  => $cf->database->password,
        "dbname"    => $cf->database->dbname,
        "charset"   => $cf->database->charset
    ]);
};


93.7k
Accepted
answer
edited Jan '16

Hey,

you could wrap your bootstrap file in a try-catch. Sample code:

try {  
    // Dependency Injector
    $di = new \Phalcon\DI\FactoryDefault();

    // ....
    // ....
    // ....

    echo $application->handle()->getContent();

} catch (Phalcon\Exception $e) {
    if ($config->debug) {
        d($e);
    } else {
        // show error to user
    }
} catch (PDOException $e){
    if ($config->debug) {
        d($e);
    } else {
        // show error to user
    }
}

$config is my personal configuration.