views:

164

answers:

1

I'm trying to figure our if there's a good or better method for handling errors in PHP than what I'm doing below. I'd like to throw an exception if there's a problem with the parse_ini_file call. This works, but is there a more elegant way to handle errors?

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  
 }
}

The __loadConfigError function just sets the __error to the error string:

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

Thanks!

+1  A: 

I usually install a global error handler to convert errors into exceptions:

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

For the rare cases, where I actually want to collect a bunch of warnings, I turn the above handler off temporarily. It's packed up nicely in a class:

/**
 * 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;
  }
}
troelskn