How To Use Error Action In Yii2?

I want to use a method to check some security settings for my user. When they do not have access, I want to send them to site/error but no matter what I do, I can’t get it to work. I have read the documentation for both Yii1 and Yii2 and I am very confused about how ErrorAction works. My config already contains the following code:




     'errorHandler' => [

            'errorAction' => 'site/error',

     ],



My controller looks something like this:




<?php

namespace app\models;

use Yii;

use yii\base\Model;

use yii\base\ErrorHandler;


class Security extends Model{

    

    /* I added this method as per documentation */

    public function actions()

    {

        return [

            'error' => [

                'class' => 'yii\web\ErrorAction',

            ],     

        ];

    }

    

    

    /* Here is my custom method to check security */

    static function auth(){

        if(Yii::$app->user->isGuest)

        {

           $message = "Access denied.";


           /* This next line shows me the error in my view, but does not redirect me to site/error 

               with the message, which is what I want. 

           */

            Yii::$app->getSession()->setFlash('error', $message); 

        }

        echo  Yii::$app->view->renderFile('site/error', $message);  //tried this, but no luck      

    }


    protected function actionError(){        

       //Is this method even needed?

    }

}



in my view file, I have:




use app\models\Security;

Security::auth();



Your controller extends from Model and does not have an action. Please read the guide to see how to create a controller.

http://www.yiiframework.com/doc-2.0/guide-controller.html

Also this section is helpful to add access control:

http://www.yiiframework.com/doc-2.0/guide-authorization.html

In general you should read the whole guide to understand all the concepts.

http://www.yiiframework.com/doc-2.0/guide-runtime-handling-errors.html#using-error-handler is helpful also for anyone else looking