Skip to content

Instantly share code, notes, and snippets.

@cspray
Created December 31, 2011 04:26
Show Gist options
  • Save cspray/1542873 to your computer and use it in GitHub Desktop.
Save cspray/1542873 to your computer and use it in GitHub Desktop.
PHP Error Handling Closure
<?php
// A closure to store error information in an array
$errors = array();
$errorCallback = function($severity, $message, $file = null, $line = null, $context = null) use (&$errors) {
$normalizeSeverity = function() use ($severity) {
$severityMap = array(
E_WARNING => 'E_WARNING',
E_NOTICE => 'E_NOTICE',
E_USER_ERROR => 'E_USER_ERROR',
E_USER_WARNING => 'E_USER_WARNING',
E_USER_NOTICE => 'E_USER_NOTICE',
E_USER_DEPRECATED => 'E_USER_DEPRECATED',
E_RECOVERABLE_ERROR => 'E_RECOVERABLE_ERROR',
E_DEPRECATED => 'E_DEPRECATED'
);
if (\array_key_exists($severity, $severityMap)) {
return $severityMap[$severity];
}
return 'E_UNKOWN_SEVERITY';
};
$index = \count($errors);
$errors[$index]['severity'] = $normalizeSeverity();
$errors[$index]['message'] = $message;
$errors[$index]['file'] = $file;
$errors[$index]['line'] = $line;
// here to return an error if improper type hints are passed
$unhandledSeverity = array(E_RECOVERABLE_ERROR);
if (\in_array($severity, $unhandledSeverity)) {
return false;
}
};
\set_error_handler($errorCallback);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment