Skip to content

Instantly share code, notes, and snippets.

@patricknelson
Last active April 14, 2016 00:28
Show Gist options
  • Save patricknelson/611cb1b5401ffea6b2eb4b8afaf3a839 to your computer and use it in GitHub Desktop.
Save patricknelson/611cb1b5401ffea6b2eb4b8afaf3a839 to your computer and use it in GitHub Desktop.
Example of how you can ensure you have programmatic encapsulation and capture of all SilverStripe generated errors.
<?php
/**
* SilverStripe doesn't typically use exceptions, but we may still need a programmatic method of encapsulating code
* and catching errors. Here we can wrap code in a callback which will trigger an exception instead of user_error()'s.
*
* @param callable $closure
* @throws Exception
*/
function withExceptions(callable $closure) {
// Override generic error handler with our own so that we can throw an exception instead.
set_error_handler(function($errno , $errstr) {
throw new Exception($errstr, $errno);
});
// Call passed closure.
$e = null;
try {
call_user_func($closure);
} catch(Exception $e) {}
// Revert back to previous error handling.
restore_error_handler();
// If an exception occurred, go ahead and throw it now (in lieu of 'finally' available in PHP 5.5 and above).
if ($e) throw $e;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment