Skip to content

Instantly share code, notes, and snippets.

@bantya
Created June 14, 2017 10:26
Show Gist options
  • Save bantya/57c7ed68f5ffd45aec9cdcce15b25606 to your computer and use it in GitHub Desktop.
Save bantya/57c7ed68f5ffd45aec9cdcce15b25606 to your computer and use it in GitHub Desktop.
PHP: Custom error and exception handler
<?php
error_reporting(E_ALL);
set_error_handler('errorHandler');
set_exception_handler('exceptionHandler');
function errorHandler ($level, $message, $file, $line)
{
if (error_reporting() !== 0) { // to keep the @ operator working
throw new \ErrorException($message, 0, $level, $file, $line);
}
}
function exceptionHandler ($exception)
{
echo "<h1>Fatal Error</h1>";
echo "<p>Uncaught exception: '" . get_class($exception) . "'</p>";
echo "<p>Message: '" . $exception->getMessage() . "'</p>";
echo "<p>Stack trace:<pre>" . $exception->getTraceAsString() . "</pre>";
echo "<p>Thrown in: '" . $exception->getFile() . "' on line '" . $exception->getLine() . "'</p>";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment