Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom views for errors in CakePHP 2.1

Tags:

php

cakephp

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

like image 347
Cameron Avatar asked Jun 02 '12 16:06

Cameron


1 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!

like image 104
Hoff Avatar answered Oct 03 '22 21:10

Hoff