It’s time for a custom error handler. The PHP core error handler is ok, but we want more.
We will implement two error handlers.
- For production
- For development
Of course you can use the production error handler in your development environment, but you will have less information 😉
You never should use the development error handler in production, because you will output to many information about your server to the user who see the error message.
To have a proper error handler we also need some mail functionality. For this we will use the PhpMailer library.
If an error occurs you should be notified immediately.
When an error occurs in my projects, I will be notified in HipChat, per mail and store the error in a logfile.
You can download the PhpMailer also here, because I had to do some changes so that the classes are Psr-1, Psr-2 and Psr-4 conform.
Free DownloadEnough of talking, let’s do some coding.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 |
<?php namespace PHPluz; use Exception; use PhpMailer\PhpMailer; use PhpMailer\PhpMailerException; /** * Class Mail * * Example usage: * $mailer = new Mail($subject, $body, $addresses, $attachments); * $mailer->sendMail(); * * @package PHPluz * * @author Janis Jekabsons <php@pluz.de> * @copyright 2016 Janis Jekabsons * @license https://opensource.org/licenses/MIT (MIT) * @version 1.0 */ class Mail extends PhpMailer { /** @var \Monolog\Logger $logger */ private $logger; /** * Constructor of Mail * * @param string $subject The Subject of the message. * @param string $body An HTML or plain text message body. If HTML then call isHTML(true). * @param array $addresses Array with mail addresses. * @param array $attachments Array with attachments (Optional) */ public function __construct($subject, $body, array $addresses, array $attachments = null) { parent::__construct(); $this->logger = Functions::createLogger('Mail'); $this->isSMTP(); $this->isHTML(true); $this->host = PHPLUZ_MAIL_HOST; $this->smtpAuth = PHPLUZ_MAIL_AUTH; $this->smtpSecure = PHPLUZ_MAIL_SECURE; $this->port = PHPLUZ_MAIL_PORT; $this->username = PHPLUZ_MAIL_USERNAME; $this->password = PHPLUZ_MAIL_PASSWORD; if ($attachments !== null) { foreach ($attachments as $attachment) { if (file_exists($attachment)) { $this->logger->addDebug("Add attachment ({$attachment})"); $this->addAttachment($attachment); } } } $this->wordWrap = 70; $this->from = PHPLUZ_MAIL_USERNAME; $this->fromName = PHPLUZ_MAIL_USER; $this->subject = $subject; $this->body = $body; foreach ($addresses as $address => $name) { $this->logger->addDebug("Add address ({$address})"); $this->addAddress($address, $name); } } /** * Function sendMail * * @return bool */ public function sendMail() { try { $this->logger->addDebug("Send mail."); return $this->send(); } catch (PhpMailerException $p) { $this->logger->addError($p->getMessage()); } catch (Exception $e) { $this->logger->addError($e->getMessage()); } return false; } } |
Now we can implement our error handler.
1. For production
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 |
<?php namespace PHPluz\Error; use ErrorException; use Exception; use PHPluz\Debug; use PHPluz\Functions; use PHPluz\Mail; /** * Class ErrorHandlerProd * * @package PHPluz\Error * * @author Janis Jekabsons <php@pluz.de> * @copyright 2016 Janis Jekabsons * @license https://opensource.org/licenses/GPL-3.0 GNU General Public License, version 3 (GPL-3.0) * @version 1.0 */ class ErrorHandlerProd { /** @var string $template */ private static $template; /** @var array $severityArray */ private static $severityArray = array(); /** @var string $errorTypeName */ private static $errorTypeName; /** @var string $errorMessage */ private static $errorMessage; /** @var string $errorFile */ private static $errorFile; /** @var int $errorLine */ private static $errorLine; /** @var array $errorTrace */ private static $errorTrace; /** @var int $errorCode */ private static $errorCode; /** @var bool $fileCheck */ private static $fileCheck; /** @var \Monolog\Logger $logger */ private static $logger; /** * Integrating the error handling * * Replaces the standard PHP error handler by their own */ public static function invokeHandler() { register_shutdown_function('PHPluz\Error\ErrorHandlerProd::checkForFatal'); set_error_handler(array('PHPluz\Error\ErrorHandlerProd', 'handler'), E_ALL); set_exception_handler('PHPluz\Error\ErrorHandlerProd::logException'); error_reporting(E_ALL); self::$logger = Functions::createLogger('ErrorHandler'); self::$template = file_get_contents(__DIR__ . DIRECTORY_SEPARATOR . 'html' . DIRECTORY_SEPARATOR . 'errorMail.html'); self::$severityArray[E_ERROR] = array( E_COMPILE_ERROR, E_CORE_ERROR, E_ERROR, E_USER_ERROR ); self::$severityArray[E_WARNING] = array( E_COMPILE_ERROR, E_COMPILE_WARNING, E_CORE_ERROR, E_CORE_WARNING, E_ERROR, E_USER_ERROR, E_USER_WARNING, E_WARNING ); self::$severityArray[E_NOTICE] = array( E_ALL, E_COMPILE_ERROR, E_COMPILE_WARNING, E_CORE_ERROR, E_CORE_WARNING, E_DEPRECATED, E_ERROR, E_NOTICE, E_RECOVERABLE_ERROR, E_STRICT, E_USER_ERROR, E_WARNING ); self::$severityArray[E_ALL] = array( E_ALL, E_COMPILE_ERROR, E_COMPILE_WARNING, E_CORE_ERROR, E_CORE_WARNING, E_DEPRECATED, E_ERROR, E_NOTICE, E_RECOVERABLE_ERROR, E_STRICT, E_USER_DEPRECATED, E_USER_ERROR, E_USER_NOTICE, E_USER_WARNING, E_WARNING ); } /** * Function logException * * @param \Exception $e * * @return bool */ public static function logException(Exception $e) { self::$errorCode = $e->getCode(); self::$errorTypeName = self::getErrorTypeName(self::$errorCode); self::$errorMessage = $e->getMessage(); self::$errorFile = $e->getFile(); self::$fileCheck = strpos(self::$errorFile, 'Error.php') !== false ? true : false; self::$errorLine = $e->getLine(); self::$errorTrace = $e->getTrace(); self::writeToFile(); PHPLUZ_MAIL_ACTIVE ? self::sendMail(self::generateFromTemplate()) : null; if (in_array(self::$errorCode, self::$severityArray[PHPLUZ_ERROR_SEVERITY])) { PHPLUZ_ERROR_PRINT_OUTPUT ? self::printError() : null; if (! headers_sent()) { header("PHP: ERROR"); } exit(88); } self::invokeHandler(); return true; } /** * Function checkForFatal */ public static function checkForFatal() { $error = error_get_last(); if ($error['type'] == E_ERROR) { self::handler($error["type"], $error["message"], $error["file"], $error["line"]); } } /** * Static method for error handling. * * Treated serious fault with the output of an error page and the demolition of the script. * * The parameters of this method are automatically like PHP. The method is integrated as a replacement for the * internal PHP error handling. * * By extending this method or the entire class, a sophisticated error handling (eg logging in database logging to * file, e-mail notice Error tracing) are implemented. * * Example for including the method: * <code> * set_error_handler(array('Error', 'handler'), (E_ALL | E_STRICT)); * * * @param int $errorNumber The PHP error code. * @param string $errorString The PHP error description. * @param string $errorFile The file in which the error occurred. * @param int $errorLine The line in $err_file in which the error occurred. * * @return bool */ public static function handler($errorNumber, $errorString, $errorFile, $errorLine) { self::logException(new ErrorException($errorString, $errorNumber, $errorNumber, $errorFile, $errorLine)); } /** * Sending of error notifications in the live system. * * @param $errorMessage * * @return bool */ public static function sendMail($errorMessage) { $serverName = filter_input(INPUT_SERVER, 'SERVER_NAME'); $computerName = filter_input(INPUT_SERVER, 'COMPUTERNAME'); $subject = "Error, Server [{$serverName}] Computer [{$computerName}] Typ [" . self::$errorTypeName . "]"; $body = $errorMessage; $mails = explode(';', PHPLUZ_ERROR_MAILS); $addresses = array(); foreach ($mails as $mail) { $addresses[$mail] = 'Error'; } $mailer = new Mail($subject, $body, $addresses); if (! $mailer->sendMail()) { die(__METHOD__ . '. There was an error sending mail: ' . $mailer->errorInfo); } return true; } /** * Static method to return the error that occurred. * * @param int $errorNumber The PHP error code. * * @return string */ private static function getErrorTypeName($errorNumber) { $errorTypes = self::getErrorTypes(); if (array_key_exists($errorNumber, $errorTypes)) { return $errorTypes[$errorNumber]; } else { return 'Unknown'; } } /** * Static method to return the supported types of errors. * * @return array */ private static function getErrorTypes() { $errorTypes = array( E_ERROR => 'Fatal run-time error', E_WARNING => 'Run-time warning', E_PARSE => 'Compile-time parse error', E_NOTICE => 'Run-time notice' ); if (defined('E_CORE_ERROR')) { $errorTypes[E_CORE_ERROR] = 'Fatal error during PHP\'s initial startup'; } if (defined('E_CORE_WARNING')) { $errorTypes[E_CORE_WARNING] = 'Warning during PHP\'s initial startup'; } if (defined('E_COMPILE_ERROR')) { $errorTypes[E_COMPILE_ERROR] = 'Fatal compile-time error'; } if (defined('E_COMPILE_WARNING')) { $errorTypes[E_COMPILE_WARNING] = 'Compile-time warning'; } if (defined('E_USER_ERROR')) { $errorTypes[E_USER_ERROR] = 'User-generated error message'; } if (defined('E_USER_WARNING')) { $errorTypes[E_USER_WARNING] = 'User-generated warning message'; } if (defined('E_USER_NOTICE')) { $errorTypes[E_USER_NOTICE] = 'User-generated notice message'; } if (defined('E_STRICT')) { $errorTypes[E_STRICT] = 'Compatibility Alert'; } if (defined('E_RECOVERABLE_ERROR')) { $errorTypes[E_RECOVERABLE_ERROR] = 'Catchable fatal error'; } if (defined('E_DEPRECATED')) { $errorTypes[E_DEPRECATED] = 'Run-time deprecated notice'; } if (defined('E_USER_DEPRECATED')) { $errorTypes[E_USER_DEPRECATED] = 'User-generated deprecated notice'; } return $errorTypes; } /** * Static Method for triggering an application error. * * This method is a wrapper for the PHP function trigger_error (). It triggers an application error with the pass * error message. * * For example for triggering an application error: * <code> * Error::trigger('Some string to output!'); * * * @param string $errorString * @param int $errorType * * @throws \Exception */ public static function trigger($errorString, $errorType = E_USER_WARNING) { throw new Exception($errorString, $errorType); } /** * Static method to output debug messages to the browser window. */ private static function printError() { if (PHPLUZ_OUTPUT_BROWSER) { $cssHelperStart = "<span style='font-weight:bold;color:#53DCCD;'>"; $cssHelperEnd = "</span>"; } else { $cssHelperStart = ""; $cssHelperEnd = ""; } $backtrace = self::doBacktrace('print'); $backtraceString = ""; $backtraceString .= "[" . date('Y-m-d H:i:s') . "] Number:\t\t " . self::$errorCode . "\n"; $backtraceString .= "[" . date('Y-m-d H:i:s') . "] Typ:\t\t " . self::$errorTypeName . "\n"; $backtraceString .= "[" . date('Y-m-d H:i:s') . "] Description:\t " . str_replace('<br>', ' ', self::$errorMessage) . "\n"; $backtraceString .= "[" . date('Y-m-d H:i:s') . "] {$cssHelperStart}File:\t\t " . self::$errorFile . " : " . self::$errorLine . "{$cssHelperEnd}\n"; $backtraceString .= "[" . date('Y-m-d H:i:s') . "] Backtrace:\n"; $backtraceString .= $backtrace; if (PHPLUZ_OUTPUT_BROWSER) { Debug::dump($backtraceString, self::$errorTypeName, false, 'print_r', self::$errorCode); } else { echo $backtraceString; } } /** * Function writeToFile */ private static function writeToFile() { $backtraceString = "\n"; $backtraceString .= "Number:\t\t " . self::$errorCode . "\n"; $backtraceString .= "Typ:\t\t " . self::$errorTypeName . "\n"; $backtraceString .= "Description:\t " . str_replace('<br>', ' ', self::$errorMessage) . "\n"; $backtraceString .= "File:\t\t " . self::$errorFile . "\n"; $backtraceString .= "Line:\t\t " . self::$errorLine . "\n"; $backtraceString .= "Backtrace:\n"; $backtraceString .= self::doBacktrace('file'); $backtraceString .= "\n"; self::errorLogging($backtraceString); } /** * Function generateFromTemplate * * @return mixed */ public static function generateFromTemplate() { $serverName = filter_input(INPUT_SERVER, 'SERVER_NAME'); $serverURL = filter_input(INPUT_SERVER, 'HTTP_HOST') . filter_input(INPUT_SERVER, 'REQUEST_URI'); $template = str_replace('{SERVER}', $serverName, self::$template); $template = str_replace('{ERROR_TYPE}', self::$errorTypeName, $template); $template = str_replace('{DATE}', date('Y-m-d H:i:s'), $template); $template = str_replace('{URL}', $serverURL, $template); $template = str_replace('{ERROR_DESCRIPTION}', self::$errorMessage, $template); $template = str_replace('{ERROR_FILE}', self::$errorFile, $template); $template = str_replace('{ERROR_LINE}', self::$errorLine, $template); $template = str_replace('{ERROR_BACKTRACE}', self::doBacktrace('generate'), $template); return $template; } /** * Function doBacktrace * * @param string $type * * @return string */ private static function doBacktrace($type) { $backtraceString = ''; if (! empty(self::$errorTrace[0]['file']) && ! empty(self::$errorTrace[0]['line'])) { if (self::$fileCheck) { self::$fileCheck = false; self::$errorFile = self::$errorTrace[0]['file']; self::$errorLine = self::$errorTrace[0]['line']; } } foreach (self::$errorTrace as $key => $value) { if ($type === 'file') { $backtraceString .= "#{$key}: Function:\t "; } elseif ($type === 'generate') { $backtraceString .= "#{$key}: Function: "; } else { $backtraceString .= "[" . date('Y-m-d H:i:s') . "] #{$key}: Function:\t "; } if (array_key_exists('object', $value)) { $backtraceString .= get_class($value['object']); $backtraceString .= $value['type']; } if (! array_key_exists('object', $value) && array_key_exists('class', $value)) { $backtraceString .= $value['class']; $backtraceString .= $value['type']; } if ($type === 'generate') { $backtraceString .= $value['function'] . "<br>"; } else { $backtraceString .= $value['function'] . "\n"; } if (array_key_exists('file', $value) && array_key_exists('line', $value)) { if (self::$fileCheck) { self::$fileCheck = false; self::$errorFile = $value['file']; self::$errorLine = $value['line']; continue; } if ($type === 'file') { $backtraceString .= "\tFile:\t {$value['file']} : {$value['line']}\n"; } elseif ($type === 'generate') { $backtraceString .= " File: {$value['file']} : {$value['line']}<br>"; } else { $backtraceString .= "[" . date('Y-m-d H:i:s') . "] File:\t {$value['file']} : {$value['line']}\n"; } } } return $backtraceString; } /** * Function errorLogging * * @param \Exception|string $error * @param bool $die */ public static function errorLogging($error, $die = false) { if ($error instanceof Exception) { self::$logger->addError($error->getMessage() . "\n" . Functions::getExceptionTraceAsString($error)); } else { self::$logger->addError($error); } ($die === true) ? exit : null; } } |
2. For development
The development error handler is original coded by Joseph Lenton.
You will find all the code in the download link below.
Now we have two error handlers in our project, but we need to activate them in our autoloader.
70 71 72 73 |
// Initialize the error handler if (PHPLUZ_ERROR_HANDLER) { ErrorInitialize::getInstance(); } |
That’s it. When an error occurs we will get a notification:
- Per mail, when “mailActive” is set to true in Config.xml
- In HipChat, when configured in Config.xml
- Logfile, when configured in Config.xml
- Terminal/Browser, when “error”->”printOutput” is set to true in Config.xml
Free DownloadThe notifications are only for the production error handler. The development error handler throws the error only to screen (in html format).
You’re welcome to make a donation if you wish