Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

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
    ]);
};


66.0k
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.