4

Is it possible to catch "Allowed memory size of [n] bytes exhausted" fatal errors in Silex using the ErrorHandler/ExceptionHandler modules?

A simple test case shows how to easily catch other kinds of fatal error - for example, the following will catch the PHP String size overflow fatal error:

use Symfony\Component\Debug\ErrorHandler;
use Symfony\Component\Debug\ExceptionHandler;

$errorHandler = function($e) {
    error_log("Caught an error!");
};

ErrorHandler::register();
$exceptionHandler = ExceptionHandler::register();
$exceptionHandler->setHandler($errorHandler);

$a = 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA';
while (true) {
    $a .= $a;
}

But this doesn't work for memory exceeded fatal errors: the following code triggers a fatal error that will not be caught:

use Symfony\Component\Debug\ErrorHandler;
use Symfony\Component\Debug\ExceptionHandler;

$errorHandler = function($e) {
    error_log("Caught an error!");
};

ErrorHandler::register();
$exceptionHandler = ExceptionHandler::register();
$exceptionHandler->setHandler($errorHandler);

$a = ['a' => ['AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA']];
while (true) {
    $a[] = $a;
}

Is it possible to catch these fatal errors using Silex, or do I need to use PHP's native register_shutdown_function instead?

kenorb
  • 155,785
  • 88
  • 678
  • 743
peter-b
  • 4,073
  • 6
  • 31
  • 43
  • 2
    No, you can't catch an error with an exception handler. You can't catch even "Memory size exhausted" errors and proceed with an exception. Because like the error says, no memory left to do anything other than throwing error and exiting. – Charlotte Dunois Aug 31 '15 at 15:29
  • Will be interesting to see how PHP7 can handle this since you should be able to catch fatal exceptions now. – Gordon Forsythe Oct 12 '15 at 21:52
  • 1
    You can also try the method in the last answer on http://stackoverflow.com/questions/8440439/safely-catch-a-allowed-memory-size-exhausted-error-in-php . The idea is to set aside a chunk of memory, then free it at the beginning of handling the error. – Gordon Forsythe Oct 12 '15 at 21:57

1 Answers1

1

As per @CharlotteDunois comment - no, you can't catch an error with an exception handler. You can't catch even "Memory size exhausted" errors and proceed with an exception. Because like the error says, no memory left to do anything other than throwing error and exiting.

Community
  • 1
  • 1
kenorb
  • 155,785
  • 88
  • 678
  • 743