puppyceceyoyo
puppyceceyoyo

Reputation: 65

Yii2, Module error page is not show but it show blank page when error 404

I have tried write my own actionError in the module DefaultController that just to render error page(HTML only for testing), it also just shows the blank page instead to show the error page.

Am I do the correct way below? It also shows blank page only when i try to access non-exist page within the module path.

In my module class, I have configured the errorHandler components within init() function as below:

public function init()   
{   
    parent::init();   
    // initialize the module with the configuration loaded from config.php   
    \Yii::configure($this, require(__DIR__ . '/config.php'));   

    \Yii::$app->setComponents([
        'errorHandler' => [
            'class' => 'yii\web\ErrorHandler',
            'errorAction' => 'studconsult/default/error',
        ] // set error action route - this to be error action in DefaultController
    ]);             
}

In my DefaultController class, I have codes below:

public function actions()   
{    
    return [    
        'error' => [    
            'class' => 'yii\web\ErrorAction',    
        ],    
    ];    
}

Upvotes: 2

Views: 6374

Answers (2)

soju
soju

Reputation: 25312

You should simply use this :

public function init()
{
    parent::init();
    Yii::$app->errorHandler->errorAction = 'studconsult/default/error';
}

Previous answer is not so nice since it will reset the component.

Upvotes: 10

Stefano Mtangoo
Stefano Mtangoo

Reputation: 6550

It seems that setComponents replaces only those components that are existing. I guess in your app config there is no such component. The easiest route I have found is create it and register it!

public function init()
{

    parent::init();   
    // initialize the module with the configuration loaded from config.php   
    \Yii::configure($this, require(__DIR__ . '/config.php'));  

    //override default error handler
    $handler = new \yii\web\ErrorHandler(['errorAction' => 'studconsult/default/error']);
    Yii::$app->set('errorHandler', $handler);
    $handler->register(); 

}

Upvotes: 3

Related Questions