Permalink
Browse files

adding some custom exceptions and exception handling

  • Loading branch information...
1 parent 151baf8 commit 257850812f28268448f03ab1d259e35d1021f817 Chris Cornutt committed Aug 7, 2012
Showing with 63 additions and 1 deletion.
  1. +42 −0 Shield/Exception.php
  2. +21 −1 Shield/Shield.php
View
@@ -0,0 +1,42 @@
+<?php
+
+/**
+ * Set of custom exceptions for Shield
+ */
+
+namespace Shield;
+
+class ShieldException extends \Exception
+{
+ public function __construct($message, $code = 0, Exception $previous = null)
+ {
+ $di = new Di();
+ $di->register(new Config($di));
+ $log = new Log($di);
+
+ $log->log($message);
+
+
+ parent::__construct($message, $code, $previous);
+ }
+
+ /**
+ * Converting the exception into a string to use for logging
+ *
+ * @return string Compiled exception string
+ */
+ public function __toString()
+ {
+ return __CLASS__ . ": [{$this->code}]: {$this->message}\n";
+ }
+}
+
+class RoutingException extends ShieldException
+{
+ public function __construct($message, $code = 0, Exception $previous = null) {
+ // nothing to see, move along
+ parent::__construct($message, $code, $previous);
+ }
+}
+
+?>
View
@@ -67,9 +67,16 @@ class Shield
*/
public function __construct()
{
+ // set the APPPATH constant
+ define('APPPATH',__DIR__.'../app');
+
// force all error messages
spl_autoload_register(array($this, '_load'));
set_error_handler(array($this, '_errorHandler'));
+ set_exception_handler(array($this, '_exceptionHandler'));
+
+ // include our exceptions
+ include_once 'Exception.php';
// make our DI container
$this->di = new Di();
@@ -194,8 +201,8 @@ public function run()
// return a 404 header
header('HTTP/1.0 404 Not Found');
- $this->di->get('Log')->log('NO ROUTE MATCH ['.strtoupper($method).']: '.$uri);
$this->throwError('No route match for "'.$uri.'"');
+ throw new RoutingException('NO ROUTE MATCH ['.strtoupper($method).']: '.$uri);
}
}
}
@@ -241,4 +248,17 @@ public function _errorHandler($errno, $errstr, $errfile, $errline)
error_log($errString.' ['.$errno.']: '.$errstr.' in '.$errfile.' on line '.$errline);
}
+
+ /**
+ * Custom exception handler
+ *
+ * @param Exception
+ *
+ * @return null
+ */
+ public function _exceptionHandler($exception)
+ {
+ $message = get_class($exception).' - '.$exception->getMessage().' [code: '.$exception->getCode().']';
+ $this->di->get('Log')->log($message);
+ }
}

0 comments on commit 2578508

Please sign in to comment.