I read that the AppError class is now for backwards compatibility and that Exceptions should be used instead. How does one go about creating custom error pages for things like 404 errors, or completely custom errors?
7 Answers
Try this:
/app/Config/core.php
Exception render need to set as an AppExceptionRender
. Example:
Configure::write('Exception', array(
'handler' => 'ErrorHandler::handleException',
'renderer' => 'AppExceptionRenderer',
'log' => true
));
/app/Controller/ErrorsController.php
class ErrorsController extends AppController {
public $name = 'Errors';
public function beforeFilter() {
parent::beforeFilter();
$this->Auth->allow('error404');
}
public function error404() {
//$this->layout = 'default';
}
}
/app/Lib/Error/AppExceptionRenderer.php
App::uses('ExceptionRenderer', 'Error');
class AppExceptionRenderer extends ExceptionRenderer {
public function notFound($error) {
$this->controller->redirect(array('controller' => 'errors', 'action' => 'error404'));
}
}
/app/View/Errors/error404.ctp
<div class="inner404">
<h2>404 Error - Page Not Found</h2>
</div>
Insert it where you need: throw new NotFoundException();
The accepted answer is not the best option because they redirect the url of your browser to http://example.com.br/error/error404
and the user can't follow what page he inputed to generate this error.
The better way to handle this situation is edit file on View/Errors/error400.ctp
, so when you input a not found url like http:example.com/crazy-wrong-url
, the browser will keep this url but render the content of the error400.ctp
file that you edit.
If you want change the layout that the view will be rendered you can type this in your view <?php $this->layout = 'error'; ?>
You can create CustomErrorPages
or Exeptions
by simply creating a class
of your error your going to show. This class needs to extend CakeExeption
. Then build your exeptionlogic and your set. Now you can just throw new <YourExeptionClass>()
and it will display an error.
Documentation: CakeExceptions