YII 如何处理自定义 404 错误页面以及其他错误页面

2022-01-04 00:00:00 http-status-code-404 php yii

我想显示 404 错误页面,因为我在我的 protected/view/system 文件夹中创建了 error404.php 文件.

I want to display 404 error page for that i have made error404.php file in my protected/view/system folder.

默认情况下,我有站点控制器,它包含如下错误操作功能

By default i have Sitecontroller and it contained error action function as below

public function actionError()
{
    if($error=Yii::app()->errorHandler->error)
    {

        if(Yii::app()->request->isAjaxRequest)
            echo $error['message'];
        else
            $this->render('error', $error);
    }
}

在主配置文件中它被定义为

inside main config file it is defined as

    'errorHandler'=>array(
        // use 'site/error' action to display errors
        'errorAction'=>'site/error',
    ),

我的问题是我只需要自定义 404 页面,其余的错误我需要按照站点控制器的错误函数处理它的方式来处理.但我找不到办法做到这一点.如果假设我从配置主中删除了errorAction"=>site/error",那么它确实通过调用

my problem is i need to customize 404 page only, rest of the error i need to handle the way it is being handle by sitecontroller's error function. But i could not find a way to do that. If suppose i remove 'errorAction'=>'site/error', from the config main then it does show the 404 error by calling

        throw new CHttpException(404, 'Page not found');

但是这样做我只能看到没有布局的页面,其他自定义错误也被视为 404 而不是.我多次阅读手册,但我仍然无法解决它.

but doing that i can only see the page without layout also other custom errors are treated same as 404 while they are not. I read the manual many times but i still cant able to resolve it.

推荐答案

将此代码用于actionError:

$app = Yii::app();
if( $error = $app->errorHandler->error->code )
{
    if( $app->request->isAjaxRequest )
        echo $error['message'];
    else
        $this->render( 'error' . ( $this->getViewFile( 'error' . $error ) ? $error : '' ), $error );
}

在视图/站点中,为 404 错误创建 error404.php,为其余错误创建 error.php.

In views/site create error404.php for 404 errors and error.php for the rest.

或者您可以在配置中为您喜欢以不同方式处理的错误定义参数并根据它检查错误代码:

Or you can define param in the config for errors you like to handle differently and check error code against it:

$app = Yii::app();
if( $error = $app->errorHandler->error->code )
{
    if( Yii::app()->request->isAjaxRequest )
        echo $error['message'];
    else    
        $this->render( 'error' . ( in_array( $error, $app->params[ 'customErrorPages' ] ) ? $error : '' ), $error );
}

错误处理程序是这样工作的:当http异常出现时,组件将检查errorAction属性中是否有任何值,如果有,将运行该控制器的动作.如果errorAction 属性没有设置值,将显示系统文件夹中的错误视图.所以不需要混合来自系统视图文件夹和控制器视图文件夹的错误视图.

Error handler works like this: when httpexception arise, component will check if there is any value in errorAction property and if there is any, will run this controller's action. If there is no set value to the errorAction property, will display error view from system folder. So there is no need to mix error views from system view folder and controller's view folder.

相关文章