2009-01-18 43 views
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; 
} 

謝謝!

回答

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; 
    } 
} 
相關問題