处理错误的方式是将其作为异常处理。最佳方法是什么?

3

我正在尝试找出PHP中处理错误的更好方法。如果parse_ini_file调用存在问题,我想抛出异常。这种方法可以运行,但是否有更优雅的方式来处理错误呢?

public static function loadConfig($file, $type)
{
    if (!file_exists($file))
    {
        require_once 'Asra/Core/Exception.php';
        throw new Asra_Core_Exception("{$type} file was not present at specified location: {$file}");
    }

    // -- clear the error
    self::$__error = null;
    // -- set the error handler function temporarily
    set_error_handler(array('Asra_Core_Loader', '__loadConfigError'));
    // -- do the parse
    $parse = parse_ini_file($file, true);
    // -- restore handler
    restore_error_handler();

    if (!is_array($parse) || is_null($parse) || !is_null(self::$__error))
    {
        require_once 'Asra/Core/Exception.php';
        throw new Asra_Core_Exception("{$type} file at {$file} appears to be    
    }
}

loadConfigError 函数只是将 __error 设置为错误字符串:

private static function __loadConfigError($errno, $errstr, $errfile, $errline)
{ 
   self::$__error = $errstr;
}

谢谢!

1个回答

5
我通常会安装一个全局错误处理程序,将错误转换为异常:
function exceptions_error_handler($severity, $message, $filename, $lineno) {
  if (error_reporting() == 0) {
    return;
  }
  if (error_reporting() & $severity) {
    throw new ErrorException($message, 0, $severity, $filename, $lineno);
  }
}
set_error_handler('exceptions_error_handler');

对于极少数需要收集大量警告的情况,我会暂时关闭上述处理程序。这个处理程序已经被封装成一个类:

/**
 * Executes a callback and logs any errors.
 */
class errorhandler_LoggingCaller {
  protected $errors = array();
  function call($callback, $arguments = array()) {
    set_error_handler(array($this, "onError"));
    $orig_error_reporting = error_reporting(E_ALL);
    try {
      $result = call_user_func_array($callback, $arguments);
    } catch (Exception $ex) {
      restore_error_handler();
      error_reporting($orig_error_reporting);
      throw $ex;
    }
    restore_error_handler();
    error_reporting($orig_error_reporting);
    return $result;
  }
  function onError($severity, $message, $file = null, $line = null) {
    $this->errors[] = $message;
  }
  function getErrors() {
    return $this->errors;
  }
  function hasErrors() {
    return count($this->errors) > 0;
  }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接