Php,有没有办法将所有通知/警告变成例外?

时间:2015-09-28 11:33:08

标签: php

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

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);

但可以变成例外吗?所以我可以看到流动。

2 个答案:

答案 0 :(得分:11)

是。 这正是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");

答案 1 :(得分:2)

是的,可以简单地完成。最好的方法是创建自己的类,该类从\ Exception和此新类的error_handler()throw对象中扩展。

你可以在

之后以简单的方式做到这一点

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

添加

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