I have a Symfony 3.2 app. I created a command to run some background task. I have to know when the command finished even if it resulted in an exception or fatal error.
My first idea was to surround my code with try/catch block. I am able to catch exceptions generated in my code or in PHP libraries as PDO but not core fatal errors. Then I tried to receive the error so I pushed a handler to the app logger. Again I intercept exceptions but not fatal errors. Here is how I add the handler to the logger:
$logger = $this->getContainer()->get('logger');
$handler = $this->getContainer()->get('app.bg_command_log_handler');
$logger->pushHandler(self::$handler);
Here is the handler:
use Monolog\Handler\AbstractProcessingHandler;
class BgCommandLogHandler extends AbstractProcessingHandler
{
protected function write(array $record)
{
var_dump($record);
}
}
Symfony version is 3.2 and PHP is 5.6.
You can set a custom error handler with
set_error_handler(), as described here.Use your error handler to
throw()exceptions when errors are raised. This way, anything that could raise a fatal error would throw an exception of your choice instead, and you'd be able to catch it.Of course, this would affect your whole application, not only this specific command. But I think it's a good thing.
As an aside, you should really try to upgrade your PHP runtime, if possible. 5.6 has not been supported for a long while.