yii 自定义错误页面,如 404、403、500

标签 yii

我正在尝试为所有错误消息使用单独的文件。 (404、403、500 等)所以我可以为它们定制设计。如果可能,我不希望页眉和页脚也包含在我的错误页面中。现在我有这个,在我的 SiteController.php 并放 error404.php 进入我的 浏览次数/站点/文件夹

public function actionError()
        {
                $error = Yii::app()->errorHandler->error;
                switch($error['code'])
                {
                        case 404:

                                $this->render('error404', array('error' => $error));
                                break;
                        .......
                        .......
                }
        }

我想知道是否有更好的方法?或者如果 Yii 有办法处理我遗漏的这个问题。

我读了这页 http://www.yiiframework.com/doc/guide/1.1/en/topics.error

它说明了将文件放入 /protected/views/system 的内容但我不太明白 Yii 的文档。

最佳答案

当您阅读时,Yii 将在 /protected/views/system 中查找文件(在查看主题后,如果有的话)

您不需要编写任何新的操作,您只需在 View 目录中创建一个文件夹系统并创建名为 errorXXX.php XXX 的文件作为错误代码。

默认页面如下所示,您可以根据需要修改它并将其保存在 /protected/views/system 中。

<body>
     <h1>Error <?php echo $data['code']; ?></h1>
     <h2><?php echo nl2br(CHtml::encode($data['message'])); ?></h2>
     <p>
        The above error occurred when the Web server was processing your request.
     </p>
     <p>
       If you think this is a server error, please contact <?php echo $data['admin']; ?>.
     </p>
     <p>
        Thank you.
     </p>
     <div class="version">
        <?php echo date('Y-m-d H:i:s',$data['time']) .' '. $data['version']; ?>
     </div>
</body>

您将可以访问 $data 中的以下属性大批
    code: the HTTP status code (e.g. 403, 500);
    type: the error type (e.g. CHttpException, PHP Error);
    message: the error message;
    file: the name of the PHP script file where the error occurs;
    line: the line number of the code where the error occurs;
    trace: the call stack of the error;
    source: the context source code where the error occurs.

另一种技术是您如何在 SiteController 中创建操作,但是要激活它,您需要更改主配置文件并将错误路由到此操作:
return array(
    ......
    'components'=>array(
        'errorHandler'=>array(
            'errorAction'=>'site/error',
        ),
    ),
);

如果您只想对错误进行皮肤处理,那么这不是必需的,如果您想执行更复杂的操作,例如将错误日志记录到数据库、向管理员发送电子邮件等,那么最好有自己的操作和附加逻辑。

关于yii 自定义错误页面,如 404、403、500,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23510026/

相关文章:

php - Yii2。动态添加属性和规则到模型

yii - 在 yii2 中,使用完整路径加载命名空间不起作用,但使用 `use` 可以

twitter-bootstrap - 如何在 Yii 框架中使用 Bootstrap 编辑变量和编译 .less?

php - Yii2 Dropzone.js 初始化不工作

php - 冒号 ( :) preceding a variable name within quotes work?

Yii CGridView 使用关系表排序和搜索

php - 试图在 Yii 中获取非对象错误的属性

javascript - 如何在 yii activeform 的 ajax 参数上传递额外的数据内容?

php - 添加 mysql 或 php 触发器以将日期时间格式从 US 更改为 UK 对于任何返回日期时间的查询

jquery - 如何更改 Yii CJuiAutoComplete 的输入类型?