0

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.

Frnak
  • 6,601
  • 5
  • 34
  • 67
  • Dont throw Exception, it 'll block you script and prevent your alternate solution to work. – ThinkTank Oct 15 '15 at 14:25
  • now receive the error in my log - still not able to catch it ... [15-Oct-2015 16:26:14 Europe/Berlin] PHP Warning: mysqli_connect(): (HY000/2002): No connection could be made because the target machine actively refused it. in C:\xampp\htdocs\finevisuals\out\script\content\classes\Database.php on line 29 [15-Oct-2015 16:26:14 Europe/Berlin] PHP Fatal error: Call to a member function set_charset() on boolean in C:\xampp\htdocs\finevisuals\out\script\content\classes\Database.php on line 31 – Frnak Oct 15 '15 at 14:27
  • those aren't execeptions. they're warnings/errors. unless your `Database` class actually throws an exception, there'll be nothing to catch. – Marc B Oct 15 '15 at 14:34
  • Well this seems to be true for the first one - however, the second is a Fatal error - shouldn't this get caught? – Frnak Oct 15 '15 at 14:39
  • 1
    fatal errors cannot be caught. that's why they're fatal. – Marc B Oct 15 '15 at 19:07

1 Answers1

1

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.

Community
  • 1
  • 1
Your Common Sense
  • 156,878
  • 40
  • 214
  • 345