CakePHP: Custom Error reporting in Console Command

2019-05-20 05:16发布

问题:

we're currently using CakePHP 2.4.7 and a custom error handler. The custom error handler works fine for every request made through HTTP or via CronDispatcher.

Unfortunately, when making a console request to one of our Console Commands, the error handler is ignored.

See the following example:

core.php:

App::uses('SentryErrorHandler', 'Sentry.Lib');

Configure::write('Sentry', array(
  //'production_only' => true, // true is default value -> no error in sentry when debug
  'PHP' => array(
    'server' => 'https://XXX:YYY@app.getsentry.com/1234'
  )
));

Configure::write('Error', array(
  'handler' => 'SentryErrorHandler::handleError',
  'level' => E_ALL & ~E_DEPRECATED,
  'trace' => true
));

Configure::write('Exception', array(
  'handler' => 'SentryErrorHandler::handleException',
  'renderer' => 'ExceptionRenderer',
  'log' => true
));

XYController.php / XYShell.php:

function test() {
  die(pr([]['test']));
}

In both cases, the correct error is thrown:

PHP Parse error:  syntax error, unexpected '[' in /vagrant/htdocs/app/Console/Command/XYShell.php on line 50

Parse error: syntax error, unexpected '[' in /vagrant/htdocs/app/Console/Command/XYShell.php on line 50
Fatal Error Error: syntax error, unexpected '[' in [/vagrant/htdocs/app/Console/Command/XYShell.php, line 50]

But when calling the mentioned method via ./cake XY test, it looks like, that the error is not properly propagated to the custom error handler.

Am I missing something?

回答1:

Console and web don't use the same config

The Exception and error config have separate options to the standard exception and error config:

consoleHandler - callback - The callback used to handle errors when running in the console. If undefined, CakePHP’s default handlers will be used.

This is also apparent from the source.

As such to configure a different handler to be used for both web and cli requests - define both the handler and consoleHandler keys:

Configure::write('Error', array(
  'handler' => 'SentryErrorHandler::handleError',
  'consoleHandler' => 'SentryErrorHandler::handleError', # <--
  'level' => E_ALL & ~E_DEPRECATED,
  'trace' => true
));

Configure::write('Exception', array(
  'handler' => 'SentryErrorHandler::handleException',
  'consoleHandler' => 'SentryErrorHandler::handleException', # <--
  'renderer' => 'ExceptionRenderer',
  'log' => true
));