ls -a
CakePHP Error Handling

So a couple of people asked me about the correct way of handling errors in CakePHP, and defining custom error pages for websites, so I decided to not explain this any more and just hand out a url to this post.

Using standard error messages

For common errors such as 404, Controller not found etc, you could easily use CakePHP’s built in cakeError function. So if you wanted to define a 404 error you would simply call the following from your controller or component:

$this->cakeError('error404');

Ok, this is all good, but what if we want more control over error handling, what if we want to define our own error handlers.

Creating custom error messages

1. Extend the default error handler by creating a file: app/app_error.php with the following definition:

<?php
class AppError extends ErrorHandler {
}?>

2. Now that you have this class all you have to do is define custom error handling functions. Include as many custom errors in this class. So lets take a situation where a user is not found in the database when people try to access domain.com/username from your site root.

function userNotFound($params) {
$this->controller->set('file', $params['username']);
$this->_outputMessage('user_not_found');
}

$this->_outputMessage(<view-filename>) will just display the view found in views/errors/<view-filename>.ctp

3. Next create the views and override the default layout.

app/views/user_not_found.ctp
<h2>User not found</h2>
<p>Sorry, but we couldn't find <?php echo $username ?>
in the system.</p>

If you want to customize the layout for your errors, simply create app/views/layouts/default.ctp and include any custom css you want. Don’t forget to include the standard $content_for_layout and $title_for_layout variables in your layout.

4. Call your custom functions from your controllers or components:

$this->cakeError('userNotFound', array('username'=>$username));

That’s pretty much it, you can now handle errors easily and elegantly :-)