Home » Php » php – Custom views for errors in CakePHP 2.1

php – Custom views for errors in CakePHP 2.1

Posted by: admin July 12, 2020 Leave a comment

Questions:

I’m looking to create custom views for errors in CakePHP 2.1

I have been reading the following question here: CakePHP 2.0 – How to make custom error pages?

BUT there are somethings that do not work as expected!

1.) Exceptions and errors do not seem to be the same thing, as if I go to a bogus url I get the built in 404 page but if I manually do a notfound exception in the controller it will call the custom view… Why is this? I thought all errors in Cake went through the exceptions?

2.) I’m trying to render a view rather than ACTUALLY redirect the user…
so for example:

App::uses('ExceptionRenderer', 'Error');

class AppExceptionRenderer extends ExceptionRenderer {
    public function notFound($error) {
        $this->controller->redirect(array('controller' => 'errors', 'action' => 'error404'));
    }
}

instead of that redirect I’m trying:

$this->controller->layout = null;
$this->controller->render('/Errors/error404');

but all I end up with is a blank page… Why is this? And this only happens when doing manual exceptions?

Can anyone answer these two questions please? Thanks

How to&Answers:

I’ve finally managed to get this figured out! Looking at the code from github, I’ve managed to get it working. Here’s my AppExceptionRenderer.php:

App::uses('ExceptionRenderer', 'Error');

class AppExceptionRenderer extends ExceptionRenderer {
    public function missingController($error) {
        $this->controller->render('/Errors/error404', 'layout');
        $this->controller->response->send();
    }

    public function missingAction($error) {
        $this->missingController($error);
    }
}

If you want to call your controller callbacks you’ll have to do something like this as well before beforeFilter():

$this->controller->beforeFilter();

That $this->controller->response->send(); line is the kicker. Hopefully this works for you!

Answer:

This is simple,

public function notFound($error) {
    $this->_outputMessage('error404');
}

That’s all what you need to do

Answer:

Simply:

throw new NotFoundException;

See the example code in the documentation about “Built in Exceptions”.

App::uses('ExceptionRenderer', 'Error'); should not be required.

For an individual view edit View/Errors/error400.ctp.