Skip to content

Instantly share code, notes, and snippets.

@mindplay-dk
Last active October 13, 2015 20:48
Show Gist options
  • Select an option

  • Save mindplay-dk/4254018 to your computer and use it in GitHub Desktop.

Select an option

Save mindplay-dk/4254018 to your computer and use it in GitHub Desktop.
Simple PHP Error-handler
/**
* Simple error-handler mapping PHP errors to PHP's ErrorException, and registering
* a global exception-handler that slightly improves Exception display.
*
* @see ErrorException
*/
class ErrorHandler
{
/**
* Register error-handler and Exception-handler.
*/
public function __construct()
{
// Convert PHP errors to ErrorException:
set_error_handler(function ($errno, $errstr, $errfile, $errline) {
if (error_reporting() === 0) {
return; // error-suppression operator was used - do not throw.
}
throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
});
// Improve Exception display in HTML response:
set_exception_handler(function (Exception $e) {
$html = true;
foreach (headers_list() as $header) {
if ((stripos($header, 'content-type:') === 0) && (stripos($header, 'html') === false)) {
$html = false; // a non-html content-type has been set
}
}
echo $html
? '<pre>' . htmlspecialchars($e->__toString()) . '</pre>'
: $e->__toString();
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment