Last active
April 14, 2016 00:28
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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