简体   繁体   中英

Cakephp3 Custom ExceptionRenderer

I am trying to build a custom exception renderer for error 404. I modified my configuration has follows:

app.php

'Error' => [
        'errorLevel' => E_ALL,
        'exceptionRenderer' => 'App\Error\AppExceptionRenderer', // use my custom renderer
        'skipLog' => [],
        'log' => true,
        'trace' => true,
    ],

and created the following script:

src/Error/AppExceptionRenderer.php

<?php
namespace App\Error;

use App\Controller\SiteHomepageController;
use Cake\View\View;
use Cake\Event\Event;
use Cake\Error\ExceptionRenderer as ExceptionRenderer;
use Cake\Network\Exception\NotFoundException as Exception;

class AppExceptionRenderer extends ExceptionRenderer {

  protected function _getController(){
    $controller = new SiteHomepageController(null,null,null);
    return $this->controller=$controller;
  }

  public function _template(Exception $exception, $method, $code)
  {
    $template = 'error';
    return $this->template = $template;
  }

  public function render(){

    $exception = $this->error;
    $code = $this->_code($exception);
    $method = $this->_method($exception);
    $template = $this->_template($exception, $method, $code);

    $this->controller->public=true;
    $this->controller->viewBuilder()->layout('site');
    $this->controller->viewBuilder()->templatePath('SiteHomepage');
    $this->controller->set('sez','');
    $this->controller->initialize();
    $this->controller->render($template);

    $event = new Event('');
    $this->controller->afterFilter($event);

    $this->controller->response->statusCode($code);

    return $this->controller->response;

  }

}

But I get the following error:

Strict (2048): Declaration of App\\Error\\AppExceptionRenderer::_template() should be compatible with Cake\\Error\\ExceptionRenderer::_template(Exception $exception, $method, $code) [APP/Error/AppExceptionRenderer.php, line 10]

I can't figure out what I am doing wrong and how to solve the problem. Any suggestions?

I figured out the problem:

in src/Error/AppExceptionRenderer.php

I replaced:

use Cake\Network\Exception\NotFoundException as Exception;

with:

use Exception;

And it works!

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