Библиотека для set_error_handler

Absinthe

жожо
Есть небольшое консольное приложение без фреймворка, на компонентах. И нужна либа для set_error_handler для конвертирования возможных notice в исключения.

Написать самому просто, копипасты на 20 строк, но не думаю, что это правильный путь.
 

c0dex

web.dev 2002-...
Команда форума
Партнер клуба
там в симфони есть компонен debug, может подойдет.
 

AnrDaemon

Продвинутый новичок
http://php.net/manual/en/class.errorexception.php#95415

Я её для себя перепилил малость.
PHP:
  /** Custom error-to-exception handler
    *
    * courtesy of [email protected]
    * http://php.net/manual/en/class.errorexception.php#95415
    * As noted below [in the discussion], it's important to realize that unless
    * caught, any Exception thrown will halt the script. So converting EVERY
    * notice, warning, or error to an ErrorException will halt your script when
    * something harmlesss like E_USER_NOTICE is triggered.
    *
    * [snip]
    *
    * Setting this function as the error handler will result in ErrorExceptions
    * only being thrown for E_USER_ERROR and E_RECOVERABLE_ERROR, while other
    * enabled error types will simply get error_log()'ed.
    *
    * It's worth noting again that no matter what you do, "E_ERROR, E_PARSE,
    * E_CORE_ERROR, E_CORE_WARNING, E_COMPILE_ERROR, E_COMPILE_WARNING, and most
    * of E_STRICT" will never reach your custom error handler, and therefore will
    * not be converted into ErrorExceptions. Plan accordingly.
    *
    * @param integer $severity PHP Error severity.
    * @param string $message Error text.
    * @param string $filename Error source file.
    * @param integer $lineno Error source line number.
    * @param mixed $context Error context.
    * @return boolean <b>FALSE</b> if error is enabled in configuration, othervise undefined.
  */
  static function errorHandler($severity, $message, $filename, $lineno, $context)
  {
    // If this error is of the enabled ones in php config (php.ini, .htaccess, etc)
    if((bool)($severity & ini_get('error_reporting')))
    {
      $e = new ErrorException($message, 0, $severity, $filename, $lineno);
      // -- FATAL ERROR
      // throw an Error Exception, to be handled by whatever Exception handling logic is available in this context
      if(in_array($severity, array(E_USER_ERROR, E_RECOVERABLE_ERROR)))
      {
        throw $e;
      }
      else if(self::debug())
      {
        if(PHP_SAPI === 'cli')
        {
          $format = '(Sev:%u) %s\nStack trace:\n%s\n  thrown in %s:%u\n';
          $trace = $e->getTraceAsString();
        }
        else
        {
          $format = '<p>(Sev:%u) %s</p>\n<pre>Stack trace:\n%s\n  thrown in <b>%s:%u</b></pre>\n';
          $message = htmlspecialchars($message);
          $filename = htmlspecialchars($filename);
          $trace = htmlspecialchars($e->getTraceAsString());
        }
        printf($format, $severity, $message, $trace, $filename, $lineno);
        // As debugging session is in progress, we keep system log clean from
        // excessive error spam, forbidding error tracking since error is displayed.
        return true;
      }

      // -- NON-FATAL ERROR/WARNING/NOTICE
      // Log the error since it's enabled
      error_log($message, 0);
      // Make sure this ends up in $php_errormsg, if appropriate
      return false;
    }
  }
 

Absinthe

жожо
@WMix, у библиотеки, судя по всему, другая задача: отображать ошибки при разработке красиво.

@AnrDaemon, мне такой код совсем не нравится.

@c0dex, то, что надо. Не знаю почему не подумал, что это доступно отдельным компонентом, думал, что часть ядра.
 

WMix

герр M:)ller
Партнер клуба
@Absinthe, да это правда (+ консолька кажись + сервер чтоб к ide биндить итд), я к тому что notice2exeption мелковато для библиотечки. а прикручивая такого коня вернешься к тем 20 строчкам как конфигурации
 

Absinthe

жожо
@AnrDaemon, нет, спасибо, я не педераст.
В свои проекты я не хочу тащить код подобного качества.
 

AnrDaemon

Продвинутый новичок
Возьми и перепиши так, как хочется.
Ей-богу, спор из-за 10 строк, которые даже поддерживать не надо.
Я эту функцию запилил 10 лет назад и она до сих пор работает без единой осечки.
 
Сверху