Php,有没有办法把所有的通知/警告变成一个异常


Php, is there a way to turn all notices/warnings into an exception?

我已经设置了错误处理程序:

set_error_handler (function($errno, $errstr, $errfile,  $errline, array $errcontext) {
  $s = date('Ymd_His');
  switch ($errno)
  {
    case E_USER_ERROR:
      $s.= '_E_';
      break;
    case E_USER_WARNING:
      $s.= '_W_';
      break;
    case E_USER_NOTICE:
      $s.= '_N_';
      break;
    default:
      $s.= '_U_';
      break;
    }
    file_put_contents (APP_PATH_CACHE.'/log'.$s.'_'.rand(1,99999).'.html', print_r(get_defined_vars(), true));
}, E_ALL);

,但它可以变成一个异常吗?这样我就能看到流程了

是。这正是创建ErrorException的原因。见http://php.net/manual/en/class.errorexception.php

function exception_error_handler($severity, $message, $file, $line) {
    if (!(error_reporting() & $severity)) {
        // This error code is not included in error_reporting
        return;
    }
    throw new ErrorException($message, 0, $severity, $file, $line);
}
set_error_handler("exception_error_handler");

是的,这很简单。最好的方法是创建自己的类,从'Exception扩展到这个新类的error_handler()抛出对象。

后面也可以用简单的方法

file_put_contents (APP_PATH_CACHE.'/log'.$s.'_'.rand(1,99999).'.html', print_r(get_defined_vars(), true));

添加

throw new Exception($errst, $errno);,第一个参数是消息,第二个参数是错误号