简体   繁体   中英

CakePHP3 - Custom page error 404 not working

I doing tutorial follow http://book.cakephp.org/3.0/en/development/errors.html#exception-renderer but it is not working and display blank page.

In config/bootstrap.php

use App\Error\AppError;
$errorHandler = new AppError();
$errorHandler->register();

In src/Error/AppError.php

<?php
namespace App\Error;

use Cake\Error\BaseErrorHandler;

class AppError extends BaseErrorHandler
{
    public function _displayError($error, $debug)
    {
        return 'There has been an error!';
    }
    public function _displayException($exception)
    {
        return 'There has been an exception!';
    }

    public function handleFatalError($code, $description, $file, $line)
    {
        return 'A fatal error has happened';
    }
}

I create my_error.ctp in src/Template/Layout/my_error.ctp. And in my src/Template/Error/error404.ctp I change layout to my_error.ctp.

$this->layout = 'my_error';

Finally, In my controller

use Cake\Network\Exception\NotFoundException;
$staff = $this->Staff->find()->where(['Staff.StaffId = '=> $id, 'Staff.PartnerId = ' =>$this->partnerId])->first();
if (empty($staff)) {
    throw new NotFoundException(__('Staff not found'));
}

Whenever encountering blank pages, enabled debug mode, visit the URL again, and check your error logs.

However, problem in this case is most likely that the docs are incorrect/misleading, as the example app error won't do anything at all. The _ prefixed methods are ment to be protected , having them return something has no effect, and handleFatalError is ment to return a boolean.

Just look at the source of Cake\\Error\\BaseErrorHandler and the core error handler Cake\\Error\\ErrorHandler , the methods that you are overwriting are ment to generate output!

You may want to report that as an issue over at GitHub .

If all you want to do, is create a custom 4xx error page, then all you need to do is to edit the src/Template/Error/error400.ctp template accordingly.

I found my mistake. :( Because in bootstrap.php I copy below code at the end of file. Therefore Cake cannot understand it. Please close this issue. Thank you for support.

use App\Error\AppError;
$errorHandler = new AppError();
$errorHandler->register();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM