Skip to content
Permalink
Browse files

Making all core classes throw CakeException subclasses, this allows d…

…evelopers to catch framework exceptions with one catch.

Adding package specific exceptions.
Replacing generic exceptions in the codebase with CakeException + package exceptions.
  • Loading branch information...
markstory committed Dec 12, 2010
1 parent 6c0efb6 commit 44c080d5ad0ef977d187b7887ccc748a836b7af5
@@ -116,7 +116,7 @@ public function validChoice($value) {
return true;
}
if (!in_array($value, $this->_choices)) {
throw new InvalidArgumentException(sprintf(
throw new ConsoleException(sprintf(
__('"%s" is not a valid value for %s. Please use one of "%s"'),
$value, $this->_name, implode(', ', $this->_choices)
));
@@ -142,7 +142,7 @@ public function validChoice($value) {
return true;
}
if (!in_array($value, $this->_choices)) {
throw new InvalidArgumentException(sprintf(
throw new ConsoleException(sprintf(
__('"%s" is not a valid value for --%s. Please use one of "%s"'),
$value, $this->_name, implode(', ', $this->_choices)
));
@@ -457,7 +457,7 @@ public function parse($argv, $command = null) {
}
foreach ($this->_args as $i => $arg) {
if ($arg->isRequired() && !isset($args[$i]) && empty($params['help'])) {
throw new RuntimeException(
throw new ConsoleException(
__('Missing required arguments. %s is required.', $arg->name())
);
}
@@ -552,7 +552,7 @@ protected function _parseShortOption($option, $params) {
*/
protected function _parseOption($name, $params) {
if (!isset($this->_options[$name])) {
throw new InvalidArgumentException(__('Unknown option `%s`', $name));
throw new ConsoleException(__('Unknown option `%s`', $name));
}
$option = $this->_options[$name];
$isBoolean = $option->isBoolean();
@@ -586,7 +586,7 @@ protected function _parseArg($argument, $args) {
}
$next = count($args);
if (!isset($this->_args[$next])) {
throw new InvalidArgumentException(__('Too many arguments.'));
throw new ConsoleException(__('Too many arguments.'));
}
if ($this->_args[$next]->validChoice($argument)) {
@@ -102,15 +102,15 @@ function __initConstants() {
protected function _initEnvironment() {
if (!$this->__bootstrap()) {
$message = "Unable to load CakePHP core.\nMake sure " . DS . 'cake' . DS . 'libs exists in ' . CAKE_CORE_INCLUDE_PATH;
throw new RuntimeException($message);
throw new CakeException($message);
}
if (!isset($this->args[0]) || !isset($this->params['working'])) {
$message = "This file has been loaded incorrectly and cannot continue.\n" .
"Please make sure that " . DIRECTORY_SEPARATOR . "cake" . DIRECTORY_SEPARATOR . "console is in your system path,\n" .
"and check the cookbook for the correct usage of this command.\n" .
"(http://book.cakephp.org/)";
throw new RuntimeException($message);
throw new CakeException($message);
}
$this->shiftArgs();
@@ -67,7 +67,7 @@ class Cache {
* @param string $name Name of the configuration
* @param array $settings Optional associative array of settings passed to the engine
* @return array(engine, settings) on success, false on failure
* @throws Exception
* @throws CacheException
*/
public static function config($name = null, $settings = array()) {
if (is_array($name)) {
@@ -113,10 +113,10 @@ protected static function _buildEngine($name) {
return false;
}
$cacheClass = $class . 'Engine';
self::$_engines[$name] = new $cacheClass();
if (!self::$_engines[$name] instanceof CacheEngine) {
throw new Exception(__('Cache engines must use CacheEngine as a base class.'));
if (!is_subclass_of($cacheClass, 'CacheEngine')) {
throw new CacheException(__('Cache engines must use CacheEngine as a base class.'));
}
self::$_engines[$name] = new $cacheClass();
if (self::$_engines[$name]->init($config)) {
if (time() % self::$_engines[$name]->settings['probability'] === 0) {
self::$_engines[$name]->gc();
@@ -249,20 +249,20 @@ public function clear($check) {
* Not implemented
*
* @return void
* @throws BadMethodCallException
* @throws CacheException
*/
public function decrement($key, $offset = 1) {
throw new BadMethodCallException(__('Files cannot be atomically decremented.'));
throw new CacheException(__('Files cannot be atomically decremented.'));
}
/**
* Not implemented
*
* @return void
* @throws BadMethodCallException
* @throws CacheException
*/
public function increment($key, $offset = 1) {
throw new BadMethodCallException(__('Files cannot be atomically incremented.'));
throw new CacheException(__('Files cannot be atomically incremented.'));
}
/**
@@ -148,11 +148,11 @@ public function read($key) {
* @param integer $offset How much to increment
* @param integer $duration How long to cache the data, in seconds
* @return New incremented value, false otherwise
* @throws RuntimeException when you try to increment with compress = true
* @throws CacheException when you try to increment with compress = true
*/
public function increment($key, $offset = 1) {
if ($this->settings['compress']) {
throw new RuntimeException(
throw new CacheException(
__('Method increment() not implemented for compressed cache in %s', __CLASS__)
);
}
@@ -166,11 +166,11 @@ public function increment($key, $offset = 1) {
* @param integer $offset How much to substract
* @param integer $duration How long to cache the data, in seconds
* @return New decremented value, false otherwise
* @throws RuntimeException when you try to decrement with compress = true
* @throws CacheException when you try to decrement with compress = true
*/
public function decrement($key, $offset = 1) {
if ($this->settings['compress']) {
throw new RuntimeException(
throw new CacheException(
__('Method decrement() not implemented for compressed cache in %s', __CLASS__)
);
}
@@ -97,18 +97,18 @@ class CakeLog {
* @param string $key The keyname for this logger, used to remove the logger later.
* @param array $config Array of configuration information for the logger
* @return boolean success of configuration.
* @throws Exception
* @throws CakeLogException
*/
public static function config($key, $config) {
if (empty($config['engine'])) {
throw new Exception(__('Missing logger classname'));
throw new CakeLogException(__('Missing logger classname'));
}
$loggerName = $config['engine'];
unset($config['engine']);
$className = self::_getLogger($loggerName);
$logger = new $className($config);
if (!$logger instanceof CakeLogInterface) {
throw new Exception(sprintf(
throw new CakeLogException(sprintf(
__('logger class %s does not implement a write method.'), $loggerName
));
}
@@ -134,7 +134,7 @@ protected static function _getLogger($loggerName) {
}
}
if (!class_exists($loggerName)) {
throw new Exception(__('Could not load class %s', $loggerName));
throw new CakeLogException(__('Could not load class %s', $loggerName));
}
return $loggerName;
}
@@ -426,7 +426,7 @@ public function __call($name, $params) {
$type = strtolower(substr($name, 2));
return $this->is($type);
}
throw new BadMethodCallException(sprintf('Method %s does not exist', $name));
throw new CakeException(__('Method %s does not exist', $name));
}
/**
@@ -448,13 +448,14 @@ public function body($content = null) {
*
* @param integer $code
* @return integer current status code
* @throws CakeException When an unknown status code is reached.
*/
public function statusCode($code = null) {
if (is_null($code)) {
return $this->_status;
}
if (!isset($this->_statusCodes[$code])) {
throw new OutOfRangeException(__('Unknown status code'));
throw new CakeException(__('Unknown status code'));
}
return $this->_status = $code;
}
@@ -265,7 +265,7 @@ public static function id($id = null) {
public static function delete($name) {
if (self::check($name)) {
if (in_array($name, self::$watchKeys)) {
trigger_error(__('Deleting session key {%s}', $name), E_USER_NOTICE);
throw new CakeSessionException(__('Deleting session key {%s}', $name));
}
self::__overwrite($_SESSION, Set::remove($_SESSION, $name));
return (self::check($name) == false);
@@ -426,7 +426,6 @@ public static function watch($var) {
*/
public static function ignore($var) {
if (!in_array($var, self::$watchKeys)) {
debug("NOT");
return;
}
foreach (self::$watchKeys as $i => $key) {
@@ -455,7 +454,7 @@ public static function write($name, $value = null) {
}
foreach ($write as $key => $val) {
if (in_array($key, self::$watchKeys)) {
trigger_error(__('Writing session key {%s}: %s', $key, var_export($val, true)), E_USER_NOTICE);
throw new CakeSessionException(__('Writing session key {%s}: %s', $key, var_export($val, true)));
}
self::__overwrite($_SESSION, Set::insert($_SESSION, $key, $val));
if (Set::classicExtract($_SESSION, $key) !== $val) {
@@ -495,7 +494,7 @@ public static function clear() {
* Sessions can be configured with a few shortcut names as well as have any number of ini settings declared.
*
* @return void
* @throws Exception Throws exceptions when ini_set() fails.
* @throws CakeSessionException Throws exceptions when ini_set() fails.
*/
protected static function _configureSession() {
$sessionConfig = Configure::read('Session');
@@ -527,7 +526,7 @@ protected static function _configureSession() {
if (!empty($sessionConfig['ini']) && is_array($sessionConfig['ini'])) {
foreach ($sessionConfig['ini'] as $setting => $value) {
if (ini_set($setting, $value) === false) {
throw new Exception(sprintf(
throw new CakeSessionException(sprintf(
__('Unable to configure the session, setting %s failed.'),
$setting
));
@@ -565,13 +564,13 @@ protected static function _getHandler($handler) {
App::import('Core', 'session/' . $class);
}
if (!class_exists($class)) {
throw new Exception(__('Could not load %s to handle the session.', $class));
throw new CakeSessionException(__('Could not load %s to handle the session.', $class));
}
$handler = new $class();
if ($handler instanceof CakeSessionHandlerInterface) {
return $handler;
}
throw new Exception(__('Chosen SessionHandler does not implement CakeSessionHandlerInterface it cannot be used with an engine key.'));
throw new CakeSessionException(__('Chosen SessionHandler does not implement CakeSessionHandlerInterface it cannot be used with an engine key.'));
}
/**
@@ -51,12 +51,12 @@ public function __construct($path = CONFIGS) {
* @param string $key The identifier to read from. If the key has a . it will be treated
* as a plugin prefix.
* @return array Parsed configuration values.
* @throws RuntimeException when files don't exist or they don't contain `$config`.
* InvalidArgumentException when files contain '..' as this could lead to abusive reads.
* @throws ConfigureException when files don't exist or they don't contain `$config`.
* Or when files contain '..' as this could lead to abusive reads.
*/
public function read($key) {
if (strpos($key, '..') !== false) {
throw new InvalidArgumentException(__('Cannot load configuration files with ../ in them.'));
throw new ConfigureException(__('Cannot load configuration files with ../ in them.'));
}
list($plugin, $key) = pluginSplit($key);
@@ -66,11 +66,11 @@ public function read($key) {
$file = $this->_path . $key . '.php';
}
if (!file_exists($file)) {
throw new RuntimeException(__('Could not load configuration file: ') . $file);
throw new ConfigureException(__('Could not load configuration file: ') . $file);
}
include $file;
if (!isset($config)) {
throw new RuntimeException(
throw new ConfigureException(
sprintf(__('No variable $config found in %s.php'), $file)
);
}
@@ -325,7 +325,7 @@ public static function drop($name) {
* @param string $key name of configuration resource to load.
* @param string $config Name of the configured reader to use to read the resource identfied by $key.
* @return mixed false if file not found, void if load successful.
* @throws Exception Will throw any exceptions the reader raises.
* @throws ConfigureException Will throw any exceptions the reader raises.
*/
public static function load($key, $config = 'default') {
if (!isset(self::$_readers[$config])) {
@@ -58,7 +58,7 @@ class AclComponent extends Component {
/**
* Constructor. Will return an instance of the correct ACL class as defined in `Configure::read('Acl.classname')`
*
* @throws Exception when Acl.classname could not be loaded.
* @throws CakeException when Acl.classname could not be loaded.
*/
public function __construct(ComponentCollection $collection, $settings = array()) {
parent::__construct($collection, $settings);
@@ -68,7 +68,7 @@ public function __construct(ComponentCollection $collection, $settings = array()
list($plugin, $name) = pluginSplit($name);
$name .= 'Component';
} else {
throw new Exception(__('Could not find %s.', $name));
throw new CakeException(__('Could not find %s.', $name));
}
}
$this->adapter($name);
@@ -84,15 +84,15 @@ public function __construct(ComponentCollection $collection, $settings = array()
*
* @param mixed $adapter Instance of AclBase or a string name of the class to use. (optional)
* @return mixed either null, or instance of AclBase
* @throws Exception when the given class is not an AclBase
* @throws CakeException when the given class is not an AclBase
*/
public function adapter($adapter = null) {
if ($adapter) {
if (is_string($adapter)) {
$adapter = new $adapter();
}
if (!$adapter instanceof AclInterface) {
throw new Exception(__('AclComponent adapters must implement AclInterface'));
throw new CakeException(__('AclComponent adapters must implement AclInterface'));
}
$this->_Instance = $adapter;
$this->_Instance->initialize($this);
@@ -387,4 +387,62 @@ class MissingTableException extends CakeException {
*/
class MissingModelException extends CakeException {
protected $_messageTemplate = 'Model %s could not be found.';
}
}
/**
* Exception class for Cache. This exception will be thrown from Cache when it
* encounters an error.
*
* @package cake.libs
*/
class CacheException extends CakeException { }
/**
* Exception class for Router. This exception will be thrown from Router when it
* encounters an error.
*
* @package cake.libs
*/
class RouterException extends CakeException { }
/**
* Exception class for CakeLog. This exception will be thrown from CakeLog when it
* encounters an error.
*
* @package cake.libs
*/
class CakeLogException extends CakeException { }
/**
* Exception class for CakeSession. This exception will be thrown from CakeSession when it
* encounters an error.
*
* @package cake.libs
*/
class CakeSessionException extends CakeException { }
/**
* Exception class for Configure. This exception will be thrown from Configure when it
* encounters an error.
*
* @package cake.libs
*/
class ConfigureException extends CakeException { }
/**
* Exception class for Xml. This exception will be thrown from Xml when it
* encounters an error.
*
* @package cake.libs
*/
class XmlException extends CakeException { }
/**
* Exception class for Console libraries. This exception will be thrown from Console library
* classes when they encounter an error.
*
* @package cake.libs
*/
class ConsoleException extends CakeException { }
Oops, something went wrong.

0 comments on commit 44c080d

Please sign in to comment.
You can’t perform that action at this time.