Text size +/-

26 Feb 08 _ Throw Down 404 Errors in Cake


By casey
in CakePHP, Casey's Corner

Say you’re doing some simple display logic for a controller view:


function view($id=null)
{
    if ($id) {
           $this->set($data,$this->Model->findById($id));
    } else {
           return false;
    }

}

In a situation like this, you always want to handle the (inevitable) situation when someone requests an invalid ID number, at which point no data would be returned in the $data variable.

Luckily, there’s a handy little function called cakeError, which lets you call a variety of Cake errors. Most of the time, you’ll want a 404 error, but it also lets you call any Cake-standard errors (you can see the full list here).

Regardless, if you want Cake to display a “404 Not Found” error message if the ID isn’t found or returns no data, do something like the following:


function view($id=null)
{
    if ($id) {
           $data = $this->Model->findById($id);
           if (!$data) {
                 $this->cakeError('error404',array(array('url'=>'/')));
           } else {
                 $this->set('data',$data);
           }

    } else {
           return false;
    }

}

That will throw up Cake’s generic 404 error page and stop further script execution for ya. If you want to have a custom 404 page, add a file named “error404.ctp” to your /app/views/error/ directory.

Spread the Word:
  • Slashdot
  • Digg
  • Facebook
  • Reddit
  • del.icio.us
  • StumbleUpon
  • Technorati
  • NewsVine


3 Responses to “Throw Down 404 Errors in Cake”

  1. Luke Says:

    hi, interesting post. I am getting problems trying to work this with Cake Beta (Jan 08), so I am guessing it is with later SVN checkouts?

    I get parameter count errors and stuff unless I do like so:
    $this->cakeError(’error404′, array($this->params['url']));

    I have turned off debugging also as that seems to interfrer with it (which makes sense).

    Like your blog - you have some good stuff here!

  2. straighten » links for 2008-02-27 Says:

    [...] The Red Frog Blog » Blog Archive » Throw Down 404 Errors in Cake (tags: cakephp 404) | | | Yahoo!ブックマークに登録 | | | [...]

  3. casey Says:

    Hey, I completely agree. Instead of using the URL params, I usually just pass it the array: array(array('url'=>'/'))

    I fixed it up in the post, thanks for pointing that out.


Leave a Reply