2
votes

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

About creating custom views for exception handling in CakePHP 2.0+ and have been using it as a base to start doing the same in my own application hence starting my own question.

However I'm not following the logic. For example how does the Throw NotFoundException know to call the notFound method in the Errors Controller as I don't see any direct relationship in terms of the naming... Unless I'm missing the point?

In any case I'm looking to add 404, 403, and 401 errors and then be able to create custom views and call them using the exception handler throughout my app.

Can anyone shed more light on this? I'm using the latest version of Cake 2.1

So I have the following code:

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

    class AppExceptionRenderer extends ExceptionRenderer {

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

And I want to replace that redirect with rendering a custom error view:

I've tried:

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

But that just shows a blank page... Can anyone help me out as I don't want to do the redirect and would much rather follow conventions and render actual views with the same url when getting errors.

Update: Also noticed that the custom views ONLY get called when exceptions are manually called in the controller, and not for actual errors such as domain.com/garbageurl or something else... So it doesn't seem to be doing what I thought!

2

2 Answers

1
votes

Have a look at these files from core Cake:

Here's what's happening:

  • ErrorHandler::handleException() is your exception handler. It gets called when an exception is thrown.
  • ErrorHandler::handleException() calls ExceptionRenderer::__construct() (your custom exception renderer must extend ExceptionRenderer) which parses the name of the Exception that was thrown, and from that, sets $this->method.
  • ErrorHandler::handleException() then calls ExceptionRenderer::render() which uses call_user_func_array() to call the method whose name is $this->method.
0
votes

I was just looking for the same thing and could not find a neat way to do this using AppExceptionRenderer. It just won't allow you to have separate error403 and error404 template files.

So I just did this in my /app/View/Errors/error400.ctp file instead...

<? if ($error instanceof ForbiddenException) { ?>

    <h4>Whoops! The page you attempted to access 
        requires permissions that you don't have.</h4>  

<? } else { ?>

    <h4>Whoops! We couldn't find the page you were looking for, sorry!</h4> 

<? } ?>