Skip to content

Instantly share code, notes, and snippets.

@thekid
Last active December 15, 2015 15:18
Show Gist options
  • Select an option

  • Save thekid/5280275 to your computer and use it in GitHub Desktop.

Select an option

Save thekid/5280275 to your computer and use it in GitHub Desktop.
Ideas for handling PHP Warnings: * begin ... rescue (inspired by Ruby) * trap
<?php
function rescue($mask, $handle) {
return function($code, $message, $file, $line, $context) use($mask, $handle) {
if ($code & $mask) {
return $handle($code, $message, $file, $line, $context);
}
};
}
function begin($try, $handle) {
set_error_handler($handle);
try {
$try();
restore_error_handler();
} catch (Exception $e) {
restore_error_handler();
throw $e;
}
}
// {{{ main
begin(function() {
trigger_error('Test');
},
rescue(E_ALL, function($code, $message, $file, $line, $context) {
printf("Caught #%d: %s @ %s:%d\n", $code, $message, $file, $line);
var_dump($context);
}));
// }}}
?>
<?php
function trap($mask, $exception, $try) {
set_error_handler(function($code, $message, $file, $line, $context) use($mask, $exception) {
if ($code & $mask) raise($exception, $message);
});
try {
$try();
restore_error_handler();
} catch (Exception $e) {
restore_error_handler();
throw $e;
}
}
// {{{ main
trap(E_ALL, 'io.IOException', function() {
trigger_error('Test');
});
// }}}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment