YII how to handle custom 404 error page along with other error pages

馋奶兔 提交于 2019-12-04 01:24:07

Use this code for 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 );
}

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 );
}

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.

Whenever errors occur, the action error in siteController is called. you can customize the error route in that action, you can do something like this:

if(404==Yii::app()->errorHandler->error->code){
     //go to custome error page
else
   //code default error.php

Can't you do this with .htaccess? Personally I create an "errors" folder with all the html php files that holds the error messages and modify .htaccess to call those pages while coming across the error.

Links:

http://www.javascriptkit.com/howto/htaccess2.shtml

http://www.addedbytes.com/for-beginners/error-documents-for-beginners/

Examples:

Create a .htaccess file in the directory you want the error pages to be called and in the text file, write the following line:

ErrorDocument 404     /404.html

assuming there is a page called 404.html in the same directory, when a 404 page not found error is genrated, the 404.html page will be called.

The same works with other error codes:

ErrorDocument 500     /500error.html

assuming a 500 error was created and a 500error.html file exists in the same directory.

In the latest versions of the framework (I am working with 1.14) use:

Yii::app()->errorHandler->error['code']

because error is an array.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!