PHP Error Handler
Hey, I thought about sharing this little piece of code. Back a couple years, I was heavily involved with PHP projects. I came up with the idea of writing an error handler class system that would allow me to add custom errors and return Boolean values from class methods and functions. It also had a method to list errors in a cleaner way than PHP’s default error handler. Here’s the concept behind it.
The way I designed this system is using a Singleton pattern to accumulate errors. By using a static variable, PHP stores this object in memory and can be referred to at a later time. Of course, there’s no real instance creation prevention in PHP, so we’ll skip the part of declaring a private constructor.
class Error { private $errorList; private $errorCount; public function getInstance() { static $errobj; if (!is_object($errobj) || !is_a($errobj, 'Error')) { $errobj = new Error(); } return $errobj; } public function raise($errCode, $errString, $errType = "general") { $errobj = self::getInstance(); $errobj->errorList[$errType][(int)$errobj->errorCount]['code'] = $errCode; $errobj->errorList[$errType][(int)$errobj->errorCount]['message'] = $errString; $errobj->errorCount++; } public function errorOccured() { $errobj = self::getInstance(); if ($errobj->errorCount > 0) { return true; } else { return false; } } public function getList() { $errobj = self::getInstance(); return $errobj->errorList; } }
Now that we have the base of our error handler class, we can create new classes that extend that master class. Here’s an example:
class ErrorDB extends Error { public function raise($db_exception, $message) { parent::raise(E_USER_WARNING, $message . "\r\n" . $db_exception->getMessage(), "database"); } }
This class will use the parent’s “raise” method to add the error to the error stack. Note that the last argument, “database” is the category in which this error will appear under. Here’s an example of how to use this class. Let’s assume that you already have a PDO database object.
<?php try { // Database operation here } catch (PDOException $e) { ErrorDB::raise($e, "Cannot perform database operation 'xyz'"); } ?>
Next, I’ll show you how to handle PHP’s native errors with the same system.
class ErrorPHP extends Error { public function raise($errno, $errstr, $errfile, $errline) { // We don't really care about E_STRICT errors if ($errno != E_STRICT) { parent::raise($errno, $errstr . " (in " . $errfile . ", at line " . $errline . ")", "PHP Errors"); } } } set_error_handler("phperror"); function phperror($errno, $errstr, $errfile, $errline) { ErrorPHP::raise($errno, $errstr, $errfile, $errline); }
Once the page is done loading, you can call the getList() statically from Error, like $errors = Error::getList();, to return a multi-dimensional array containing all the errors that occured. You’re free to display it anyway you’d like.
I hope you find this article useful!
Thanks for reading.