#StackBounty: #php #php-7 set_exception_handler Not Catching Class Exceptions

Bounty: 50

I’ve searched a lot here and generally, and have tried everything I can think of before posting, but I cannot nut this out. I’m sure a decent php person will know straight away what the issue is , so …

I have a file Db.php which contains abstract class Db which has require_once Config.php.

Config.php contains, among other things:

function global_exception_handler($e) {
    mail(ADDR_TO, "Error", "ERROR: $e", "From: ".ADDR_FM);
}

set_exception_handler('global_exception_handler');

:: If I throw an exception – eg, throw new Exception("Test"); – from below this code in Config.php, it works (email received).

:: If I throw an exception outside of the Db class in Db.php, it works.

:: But if I throw an exception from within the Db class – eg in the constructor, where I perform a connection test – nothing happens.

Even if I move the global_exception_handler function and set_exception_handler declaration to the Db class (using the class form @set_exception_handler(array($this, 'global_exception_handler'))), it doesn’t fire.

I know I must be missing something obvious, though I’m virtually certain this was working before Hostgator upgraded our server from php 5.5 to 7.4.


To answer @WesselvanderLinden’s questions and code request …

  1. The (very simple) Db class constructor code is executing, and only once; I added trace mail alert in there as per the error handler to test for this.

  2. The constructor originally had a Try...Catch and I was throwing the exception in the Catch after a couple of housekeeping statements. I removed all the "noise" and reduced the constructor down to bare-bones.

  3. The Config.php file is included (require_once) in the Db.php file and the handler statements are as posted above.

Here’s the bare-bones Db class constructor code (with commented run check trace email):

require_once "Config.php";

abstract class Db {

    public function __construct() {
        //mail(ADDR_TO, "Database Error", "ERROR!", "From: ".ADDR_FM);
        throw new Exception("Database connection failed");
    }
}


Get this bounty!!!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.