CakePHP 2.0+ 使用异常的自定义错误视图


CakePHP 2.0+ custom error views using exceptions

我一直在这里阅读以下问题:CakePHP 2.0 - 如何制作自定义错误页面?

关于在 CakePHP 2.0+ 中为异常处理创建自定义视图,并一直使用它作为基础开始在我自己的应用程序中执行相同的操作,因此开始我自己的问题。

但是我没有遵循逻辑。例如,Throw NotFoundException 如何知道在错误控制器中调用 notFound 方法,因为我在命名方面没有看到任何直接关系......除非我错过了重点?

无论如何,我希望添加 404、403 和 401 错误,然后能够创建自定义视图并在整个应用程序中使用异常处理程序调用它们。

谁能对此有更多的了解?我使用的是最新版本的蛋糕 2.1

所以我有以下代码:

    App::uses('ExceptionRenderer', 'Error');
    class AppExceptionRenderer extends ExceptionRenderer {
        public function notFound($error) {
            $this->controller->redirect(array('controller' => 'errors', 'action' => 'error404'));
        }
}

我想用呈现自定义错误视图来替换该重定向:

我试过:

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

但这只显示一个空白页...任何人都可以帮助我,因为我不想进行重定向,并且宁愿遵循约定并在出现错误时使用相同的 url 呈现实际视图。

更新:还注意到自定义视图仅在控制器中手动调用异常时才被调用,而不是针对实际错误(例如domain.com/garbageurl或其他错误)...所以它似乎没有像我想的那样!

看看 core Cake 中的这些文件:

    蛋糕/错误
  • /错误处理程序.php
  • 蛋糕/错误/异常渲染器.php
以下是

正在发生的事情:

  • ErrorHandler::handleException()是异常处理程序。当引发异常时,将调用它。
  • ErrorHandler::handleException()调用ExceptionRenderer::__construct()(您的自定义异常呈现器必须扩展ExceptionRenderer),它解析引发的异常的名称,并从中设置$this->method
  • 然后ErrorHandler::handleException()调用ExceptionRenderer::render()它使用 call_user_func_array() 调用名称为 $this->method 的方法。

我只是在寻找同样的东西,找不到一种巧妙的方法来使用 AppExceptionRenderer 来做到这一点。 它只是不允许您拥有单独的 error403 和 error404 模板文件。

所以我只是在我的/app/View/Errors/error400.ctp文件中这样做了......

<? 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> 
<? } ?>