Darren O'Neill - Blog

Custom error pages in CakePHP

Programming Web

I needed to create some custom error handling functionality on a CakePHP project I was working on a little while ago. The site URL contained tracking variables and I didn’t want them to be lost if the people linking to the site got the URL or their individual tracking codes slightly wrong and were in turn redirected to domain.com/pages/home.

I could have created the template error404.ctp under /views/errors/ and written any URL parsing functionality there but coding any PHP logic in a HTML template is not recommended in the MVC framework paradigm. It is worth noting that CakePHP allows you to create the following error templates under /views/errors/ that are great if you just want custom error pages without the need for any PHP code:
error404.ctp
missing_action.ctp
missing_component_class.ctp
missing_component_file.ctp
missing_connection.ctp
missing_controller.ctp
missing_helper_class.ctp
missing_helper_file.ctp
missing_layout.ctp
missing_model.ctp
missing_scaffolddb.ctp
missing_table.ctp
missing_view.ctp
private_action.ctp
scaffold_error.ctp

As I did have a requirement to write some PHP code I created the file app_error.php under the root directory:

class AppError extends ErrorHandler {
public function error404($arg) {
// If someone arrives here - let's keep the tracking codes
$url = $arg['url'];
$url_string = "";
// ...
$this->controller->redirect("/pages/mainpage/" . $url_string);
exit();
}
}

As can be seen, you just need to create a function named the same as the error. In this example I am not using the error404.ctp template after processing, instead redirecting to another static page with the tracking codes appended to the end of the URL.

Recent

Latest Tweet

Fetching latest tweet...

On the web