Last active
December 16, 2015 12:29
-
-
Save mamuz/5435334 to your computer and use it in GitHub Desktop.
Converting php errors into an exception
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class ConvertError2Exception | |
{ | |
/** | |
* Error string. | |
* Is null if there was no error | |
* | |
* @var string | |
*/ | |
protected $_errorStr = null; | |
/** | |
* Handle any errors | |
* | |
* @param integer $errno | |
* @param string $errstr | |
* @param string $errfile | |
* @param integer $errline | |
* @return void | |
*/ | |
protected function _errorHandler($errno, $errstr, $errfile, $errline) | |
{ | |
if (null === $this->_errorStr) { | |
$this->_errorStr = $errstr; | |
} else { | |
$this->_errorStr .= PHP_EOL . $errstr; | |
} | |
} | |
/** | |
* Example for using errorHandler: | |
* Load the INI file from disk using parse_ini_file(). Use a private error | |
* handler to convert any loading errors into an Exception | |
* | |
* @param string $filename | |
* @throws Exception | |
* @return array | |
*/ | |
protected function _parseIniFile($filename) | |
{ | |
set_error_handler(array($this, '_errorHandler')); | |
$iniArray = parse_ini_file($filename, true); // Warnings and errors are suppressed | |
restore_error_handler(); | |
// Check if there was an error while loading file | |
if ($this->_errorStr !== null) { | |
throw new Exception($this->_errorStr); | |
} | |
return $iniArray; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment