ErrorHandler.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. <?php
  2. namespace Tools\Error;
  3. use Cake\Core\Configure;
  4. use Cake\Error\ErrorHandler as CoreErrorHandler;
  5. use Cake\Log\Log;
  6. use Exception;
  7. /**
  8. * Custom ErrorHandler to not mix the 404 exceptions with the rest of "real" errors in the error.log file.
  9. *
  10. * All you need to do is:
  11. * - switch `use Cake\Error\ErrorHandler;` with `use Tools\Error\ErrorHandler;` in your bootstrap
  12. * - Make sure you got the 404 log defined either in your app.php or as Log::config() call.
  13. *
  14. * Example config as scoped one:
  15. * - 'className' => 'Cake\Log\Engine\FileLog',
  16. * - 'path' => LOGS,
  17. * - 'file'=> '404',
  18. * - 'levels' => ['error'],
  19. * - 'scopes' => ['404']
  20. *
  21. * If you don't want the errors to also show up in the debug and error log, make sure you set
  22. * `'scopes' => false` for those two in your app.php file.
  23. *
  24. * In case you need custom 404 mappings for some additional custom exceptions, make use of `log404` option.
  25. * It will overwrite the current defaults completely.
  26. */
  27. class ErrorHandler extends CoreErrorHandler {
  28. /**
  29. * Handles exception logging
  30. *
  31. * @param \Exception $exception Exception instance.
  32. * @return bool
  33. */
  34. protected function _logException(\Exception $exception) {
  35. $blacklist = [
  36. 'Cake\Routing\Exception\MissingControllerException',
  37. 'Cake\Routing\Exception\MissingActionException',
  38. 'Cake\Routing\Exception\PrivateActionException',
  39. 'Cake\Routing\Exception\NotFoundException',
  40. 'Cake\Datasource\Exception\RecordNotFoundException',
  41. 'Cake\Network\Exception\MethodNotAllowedException',
  42. 'Cake\Network\Exception\BadRequestException',
  43. 'Cake\Network\Exception\ForbiddenException',
  44. 'Cake\Network\Exception\GoneException',
  45. 'Cake\Network\Exception\ConflictException',
  46. 'Cake\Network\Exception\InvalidCsrfToken',
  47. 'Cake\Network\Exception\UnauthorizedException',
  48. 'Cake\Network\Exception\NotAcceptableException',
  49. ];
  50. if (isset($this->_options['log404'])) {
  51. $blacklist = $this->_options['log404'];
  52. }
  53. if ($blacklist && in_array(get_class($exception), (array)$blacklist)) {
  54. $level = LOG_ERR;
  55. Log::write($level, $this->_getMessage($exception), ['404']);
  56. return false;
  57. }
  58. return parent::_logException($exception);
  59. }
  60. }