Custom CakePHP Errors - A Complete Run Down

Taking advantage of custom error documents usually requires tapping on an .htaccess file, as discussed in my previous custom error article. However CakePHP makes for easy custom error handling thanks to a pre-defined Cake system.

I’ll walk you through creating custom error pages, both simple and complex.

Basic Errors

Creating typical custom error pages in Cake is super easy. Below is a list of files that can be created in the /app/views/errors/ folder in order to overwrite the generic error templates located in /cake/libs/view/templates/errors/:

# not found #
    error404.thtml

# missing files #
    missing_action.thtml
    missing_component_class.thtml
    missing_component_file.thtml
    missing_connection.thtml
    missing_controller.thtml
    missing_helper_class.thtml
    missing_helper_file.thtml
    missing_layout.thtml
    missing_model.thtml
    missing_scaffolddb.thtml
    missing_table.thtml
    missing_view.thtml

# private & scaffold related errors #
    private_action.thtml
    scaffold_error.thtml

The above errors are all fine and dandy, but what if you want to create a custom error to be displayed when a user is denied access to the super secret area of your website?

Custom Errors

Custom errors could be used for anything - to let users know an area is restricted, or perhaps to users know they need to pay you loads of cash in order to use your website. Whatever the reason, Cake can help.

Example:
Let’s say you want your users to donate before entering your website. For those who haven’t donated, you want to display an “error”.

First create your donation error page as you would any of the errors above, and place it in the typical errors folder:

/app/views/errors/donation_error.thtml

Next, in order to call your custom error, place the following in your controller of choice:

$this->viewPath = 'errors';
$this->render('donation_error');

Give yourself a pat on the back. You’ve done well.

2 Comments so far

  1. defunk on January 23rd, 2008

    thx m8! short and absolutely to the point :)

  2. xclusiv on July 28th, 2008

    Cool Content!! Thanks!!

Leave a Reply