PHP   发布时间:2022-04-05  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了php-将错误作为异常处理.最好的方法?大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

我试图找出是否有比我在下面做的更好或更好的方法来处理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    
    }
}
@H_502_7@

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

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

谢谢!

解决方法:

我通常会安装一个全局错误处理程序以将错误转换为异常:

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');
@H_502_7@

在极少数情况下,我实际上想收集一堆警告,我会暂时关闭上述处理程序.它很好地包装在一个类中:

/**
 * 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 one rror($severity, $message, $file = null, $line = null) {
    $this->errors[] = $message;
  }
  function getErrors() {
    return $this->errors;
  }
  function hasErrors() {
    return count($this->errors) > 0;
  }
}
@H_502_7@

大佬总结

以上是大佬教程为你收集整理的php-将错误作为异常处理.最好的方法?全部内容,希望文章能够帮你解决php-将错误作为异常处理.最好的方法?所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: