Throwing exceptions when appropriate is a much cleaner way to handle errors in your PHP applications than the usual return false; and the inevitable if statement to check whether your method call worked. Not only does it make your code cleaner, you actually get some information about the error.
In a CakePHP MVC structure it’s fun to throw Exceptions from your models, but including a try/catch in every single controller method starts to get unwieldy. Instead you can create an exception handler in your AppController, something like this:
public function beforeFilter()
{
set_exception_handler(array($this, 'handleException'));
parent::beforeFilter();
}
public function handleException(Exception $exception)
{
try
{
throw $exception;
}
catch (ResourceNotFoundException $ex)
{
$this->cakeError('error404', array('message' => $ex->getMessage()));
}
catch (Exception $ex)
{
$this->cakeError('error500', array('message' => $ex->getMessage()));
}
}
Notice that we can rethrow the exception in the handler to avoid using an if or switch construct. Now in our controller method we can write code like this:
$bagpuss = $this->Bagpuss->read(null, $id);
if (!$bagpuss)
{
throw new ResourceNotFoundException('Could not find bagpuss');
}
We could even go as far as to override read() in AppModel to throw a ResourceNotFoundException to simplify our controllers further, though I worry this will (a) break existing tools (change of contract), and (b) create too much dependency between model and controller.
Comments or suggestions welcome.