error-handling - 了解 cakephp3 错误处理

标签 error-handling cakephp-3.0

我想通过使用我的 AppController“initilize()”方法的子函数检查数据库表中的维护标志来为我的蛋糕网站创建一个维护页面。如果设置了该标志,我会抛出自定义 MaintenanceException(当前不包含任何特殊内容):

class MaintenanceException extends Exception{

} 

为了处理它,我实现了一个自定义应用程序异常渲染器:

class AppExceptionRenderer extends ExceptionRenderer {
    public function maintenance($error)
    {
        return "MAINTENANCE";
    }
} 

如果我将数据库标志设置为 true,我就可以在我的网站上看到此维护文本,但我在 cake 的错误处理文档 ( http://book.cakephp.org/3.0/en/development/errors.html ) 中找不到任何关于如何进行维护的信息实际上可以告诉异常渲染器使用模板“infopage”渲染 View “maintenance”

我可以在没有自定义错误 Controller 的情况下使用ExceptionRenderer来使用该函数吗?如果不是,正确的 ErrorController 实现应该是什么样子?我已经尝试过这个:

class AppExceptionRenderer extends ExceptionRenderer {

    protected function _getController(){
        return new ErrorController();
    }

    public function maintenance($error)
    {
        return $this->_getController()->maintenanceAction();
    }

} 

与:

class ErrorController extends Controller {

    public function __construct($request = null, $response = null) {
        parent::__construct($request, $response);
        if (count(Router::extensions()) &&
            !isset($this->RequestHandler)
        ) {
            $this->loadComponent('RequestHandler');
        }
        $eventManager = $this->eventManager();
        if (isset($this->Auth)) {
            $eventManager->detach($this->Auth);
        }
        if (isset($this->Security)) {
            $eventManager->detach($this->Security);
        }
        $this->viewPath = 'Error';
    }

    public function maintenanceAction(){
        return $this->render('maintenance','infopage');
    }

} 

但这只会引发 NullPointerExceptions 和 fatal error 。我对蛋糕手册也很失望,因为那里的代码示例根本无法让我了解如何完成任何事情以及我实际拥有什么功能。

最佳答案

因为我今天有更多时间,所以我花了一个小时深入研究蛋糕源代码并找到了一个适合我的解决方案(并且可能是应该完成的方式,尽管蛋糕文档并没有真正给出提示):

第 1 步:在您自己的类中重写 ExceptionRenderer_template(...) 方法。就我而言,我复制了父级的方法并在方法的开头添加了以下代码:

$isMaintenanceException = $exception instanceof MaintenanceException;

if($isMaintenanceException){
    $template = 'maintenance';
    return $this->template = $template;
}

这告诉我们的渲染器,名为“maintenance”的错误模板(应位于文件夹:/Error 中)是它应渲染的错误页面内容。

第2步:我们现在要做的唯一一件事(在我看来这有点hacky,但蛋糕文档以这种确切的方式提出)是在我们的template 为我们想要渲染的基本布局的名称。因此,只需在错误模板顶部添加以下代码即可:

$this->layout = "infopage";

我创建的错误 Controller 实际上甚至不需要这种方法,而且我仍然不知道蛋糕错误 Controller 实际上是如何工作的。如果我有更多时间,也许我会深入研究这个问题,但目前是这样。

关于error-handling - 了解 cakephp3 错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28309945/

相关文章:

python - 我在任何地方都找不到我的错误

Javascript-根据 URL 的最后一个字符串动态更改背景图像

CakePHP 3 $this->模型->有条件获取?

python - 从Python SDK调用时,从Azure存储 “connection reset” 10054错误中恢复的正确方法是什么?

javascript - Dojo require,模块加载失败时连接报错

python - 运行 'classloop'时出错

java - 重新加载 jsf 表单错误上的某个 jQuery 代码

php - 具有 TranslateBehaviour 的实体的非翻译属性

php - 如何将 CakePHP 专用于 API?

php - CakePHP 3 的 OAuth2 身份验证