Is there way to use a custom exception handler, instead of the default exception handler, inside a class's __destruct method?
For example:
function myExceptionHandler($e)
{
echo "custom exception handler";
if(is_object($e) && method_exists($e,'getMessage'))
echo $e->getMessage();
}
set_exception_handler('myExceptionHandler');
class MyClass {
public function __construct()
{
// myExceptionHandler handles this exception
//throw new Exception("Exception from " . __METHOD__);
}
public function doStuff()
{
// myExceptionHandler handles this exception
//throw new Exception("Exception from " . __METHOD__);
}
public function __destruct()
{
// default exception handler
throw new Exception("Exception from " . __METHOD__);
}
}
$myclass = new MyClass();
$myclass->doStuff();
Even if set_exception_handler is called within the __destruct method, the default handler is still used:
public function __destruct()
{
$callable = function($e)
{
echo "custom exception handler".PHP_EOL;
if(is_object($e) && method_exists($e,'getMessage'))
echo $e->getMessage();
};
set_exception_handler($callable);
throw new Exception("Exception from " . __METHOD__); // default exception handler
}