code_junkie

Handling errors as exceptions. Best methods

Nov 13th, 2011
135
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.86 KB | None | 0 0
  1. public static function loadConfig($file, $type)
  2. {
  3. if (!file_exists($file))
  4. {
  5. require_once 'Asra/Core/Exception.php';
  6. throw new Asra_Core_Exception("{$type} file was not present at specified location: {$file}");
  7. }
  8.  
  9. // -- clear the error
  10. self::$__error = null;
  11. // -- set the error handler function temporarily
  12. set_error_handler(array('Asra_Core_Loader', '__loadConfigError'));
  13. // -- do the parse
  14. $parse = parse_ini_file($file, true);
  15. // -- restore handler
  16. restore_error_handler();
  17.  
  18. if (!is_array($parse) || is_null($parse) || !is_null(self::$__error))
  19. {
  20. require_once 'Asra/Core/Exception.php';
  21. throw new Asra_Core_Exception("{$type} file at {$file} appears to be
  22. }
  23. }
  24.  
  25. private static function __loadConfigError($errno, $errstr, $errfile, $errline)
  26. {
  27. self::$__error = $errstr;
  28. }
  29.  
  30. function exceptions_error_handler($severity, $message, $filename, $lineno) {
  31. if (error_reporting() == 0) {
  32. return;
  33. }
  34. if (error_reporting() & $severity) {
  35. throw new ErrorException($message, 0, $severity, $filename, $lineno);
  36. }
  37. }
  38. set_error_handler('exceptions_error_handler');
  39.  
  40. /**
  41. * Executes a callback and logs any errors.
  42. */
  43. class errorhandler_LoggingCaller {
  44. protected $errors = array();
  45. function call($callback, $arguments = array()) {
  46. set_error_handler(array($this, "onError"));
  47. $orig_error_reporting = error_reporting(E_ALL);
  48. try {
  49. $result = call_user_func_array($callback, $arguments);
  50. } catch (Exception $ex) {
  51. restore_error_handler();
  52. error_reporting($orig_error_reporting);
  53. throw $ex;
  54. }
  55. restore_error_handler();
  56. error_reporting($orig_error_reporting);
  57. return $result;
  58. }
  59. function onError($severity, $message, $file = null, $line = null) {
  60. $this->errors[] = $message;
  61. }
  62. function getErrors() {
  63. return $this->errors;
  64. }
  65. function hasErrors() {
  66. return count($this->errors) > 0;
  67. }
  68. }
Add Comment
Please, Sign In to add comment