CodeIgniter Forums
How to catch db_connect Exception? - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: CodeIgniter 4 (https://forum.codeigniter.com/forumdisplay.php?fid=28)
+--- Forum: CodeIgniter 4 Support (https://forum.codeigniter.com/forumdisplay.php?fid=30)
+--- Thread: How to catch db_connect Exception? (/showthread.php?tid=87135)



How to catch db_connect Exception? - 5flex - 03-16-2023

Hello!
In my code I have
PHP Code:
$DB db_connect(self::DB_GROUP); 

If DB_GROUP is wrong I have "ERROR - 17-03-2023 07:39:36 --> Error connecting to the database: mysqli_sql_exception: Access denied for user"
How I can cover this code in Exception?


PHP Code:
try {
    $DB db_connect(self::DB_GROUP);
} catch (
DatabaseException Exception $e) {
    log_message('error'"Could not connect to external database");
    return [];


But this block try...catch is not working...I have no log message and my script is falling, but I want execute return [].


P.S. I found a solution, but I don't like it at all

PHP Code:
if ($DB db_connect(self::DB_GROUP)) {
    try {
    // ...my query
    } catch(DatabaseException $e) {
        return ['error' => 'error']
    }