peter-b
peter-b

Reputation: 4191

Catch "Allowed memory size exhausted" fatal errors in Silex

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?

Upvotes: 4

Views: 3718

Answers (1)

kenorb
kenorb

Reputation: 166737

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.

Upvotes: 1

Related Questions