Frnak
Frnak

Reputation: 6802

PHP cannot catch Error from within included file

i try to implement a fallback solution for when my database is not available. Somhow i do not manage to catch the error.

Call to create connection:

if(!$this->connection = mysqli_connect(
        $this->host,
        $this->name,
        $this->pass,
        $this->db
    )) { throw new Exception('Unable to connect to Database'); }

init.php to include dbClass

require_once __DIR__ . '/../classes/Database.php';
$db = new Database();
$connection = $db->getConnection();

actual usage with try catch wrap

try {
        include __DIR__ . '/../out/script/content/config/init_direct.php';
        ... do stuff regulary
}catch (Exception $e) {
        ... do fallback stuff
}

i do not get into the catch block. for test purpose i just set the database offline.

Upvotes: 0

Views: 93

Answers (1)

Your Common Sense
Your Common Sense

Reputation: 157896

there are several problems with your approach

  • First, your problem is insufficient debugging. You just assume that exception has been thrown, but in reality it weren't.
  • Second, this happened because mysqli_connect returns an object, not boolean you expect.
  • Third, as you've been told in the comments, errors aren't exceptions and you cannot catch them.

Anyway, with mysqli you don't need to throw exceptions manually - this extension can throw them by itself, so, all you need is to set the proper mode up - an exception will be thrown which will be caught all right.

Upvotes: 1

Related Questions