Last active
November 13, 2020 15:22
-
-
Save Dormilich/418018763dfd098c663a to your computer and use it in GitHub Desktop.
Extensible error handling class
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 | |
namespace Dormilich\Core; | |
/** | |
* Set a custom error handler that is valid as long as this instance is not | |
* garbage collected. | |
*/ | |
class ErrorHandler | |
{ | |
/** | |
* Set a new error handler from this class’ static methods. | |
* | |
* @param (string) $handler Name of a static method of this class. | |
* @return (self) | |
* @throws (BadMethodCallException) Undefined method. | |
*/ | |
public function __construct($handler = 'throwError') | |
{ | |
if (!method_exists(__CLASS__, $handler)) { | |
throw new \BadMethodCallException('Unknown error handler requested.'); | |
} | |
set_error_handler([__CLASS__, $handler]); | |
} | |
/** | |
* Reset the error callback to the previous handler when the object is destroyed. | |
*/ | |
public function __destruct() | |
{ | |
restore_error_handler(); | |
} | |
/** | |
* Convert errors/warnings/notices into an error exception. | |
* Note that throwing an exception does not reset the error handler. | |
* | |
* @param (integer) $code One of the PHP error constants. | |
* @param (string) $msg The error message. | |
* @param (string) $file The filename that the error was raised in. | |
* @param (integer) $line The line number the error was raised at. | |
* @return (void) | |
* @throws (ErrorException) The error as exception. | |
*/ | |
final public static function throwError($code, $msg, $file, $line) | |
{ | |
throw new \ErrorException($msg, $code, 1, $file, $line); | |
} | |
/** | |
* Do whatever needs to be done with the error. | |
* | |
* @param (integer) $errno The level of the error raised. | |
* @param (string) $errstr The error message. | |
* @param (string) $errfile The filename that the error was raised in. | |
* @param (integer) $errline The line number the error was raised at. | |
* @param (array) $errcontext An array of every variable that existed in | |
* the scope the error was triggered in. | |
* @return (boolean) If the function returns FALSE then the normal | |
* error handler continues. | |
*/ | |
public static function handleError($errno, $errstr) | |
{ | |
// ... | |
return TRUE; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment