0
votes

I have create a class method that creating a Datasource on the fly in order to check if the given database connection information is correct. The array that hold the information for the connection is in the following form:

Array
(
    [datasource] => Database/Mysql
    [persistent] => 0
    [host] => localhost
    [login] => root
    [password] => 
    [database] => wp33
    [prefix] => dr_
    [encoding] => UTF8
    [port] => 
)

and my method has that code in it:

@App::import('Model', 'ConnectionManager');

ConnectionManager::create('Default', $config);
$db = ConnectionManager::getDataSource('default');

if(!$db->isConnected())
{
    $this->Session->setFlash(__d('dir', 'Could not connect to database.'), 'Flash/error');
    return;
}

Note that $config hold the data from the above array.

The problem is that the method code return that error:

Missing Database Connection Error: SQLSTATE[42000] [1049] Unknown database 'wp33' requires a database connection Error: Confirm you have created the file : app\Config\database.php.

because the database shema wp33 does not exists in my database server.

What I like to do is to stop that error from CakePHP side and display an error to my client with $this->Session->setFlash instead of the default CakePHP error.

Is there any good idea ?

1

1 Answers

2
votes

Catch the MissingDatabaseException and use getMessage() to set the error message to the session flash.

try {
    ConnectionManager::create('Default', $config);
    $db = ConnectionManager::getDataSource('default');
} catch (MissingDatabaseException $e) {
    $this->Session->setFlash($e->getMessage()); 
}

Something like this.