How to load an errorHandler in a module?

Hello,

Basically i have an error handler for the front-end of the application located in /config/web.php in components like this:


'errorHandler' => [

            'errorAction' => 'site/error',

        ]

but i also have an admin section (adminLTE) for the app and i’m trying to add a separate errorHandler than the public one, and i tried like this, in /modules/admin/config/main.php:


return [

    'id'=> 'admin',

    'components' => [

        'errorHandler' => [

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

            'errorAction' => 'admin/admin/error',

        ],

    ]

];

my Module.php looks like this:


class Module extends \yii\base\Module

{

    /**

     * @inheritdoc

     */

    public $controllerNamespace = 'app\modules\admin\controllers';


    /**

     * @inheritdoc

     */

    public function init()

    {

        parent::init();

        Yii::$app->name='admin';


        // Custom config for admin module

        Yii::configure($this, require(__DIR__ .DIRECTORY_SEPARATOR.'config'.DIRECTORY_SEPARATOR .'main.php'));




    }




}

So how can i have two separate errorHandlers one for front-end and the other in the module ?

Thank you!

You need to actually override application error handler with module’s one:




/** @var ErrorHandler $handler */

$handler = $this->get('errorHandler');

\Yii::$app->set('errorHandler', $handler);

$handler->register();



hey Sam,

Thanks for your answer, but can you please tell me where should i put this code? how can i override the application errorHandler with the module errorHandler for modules errors only ?

Thanks!

Module’s init() method:




class Module extends \yii\base\Module

{

    public function init()

    {

        parent::init();

        \Yii::configure($this, [

            'components' => [

                'errorHandler' => [

                    'class' => ErrorHandler::className(),

                ]

            ],

        ]);


        /** @var ErrorHandler $handler */

        $handler = $this->get('errorHandler');

        \Yii::$app->set('errorHandler', $handler);

        $handler->register();

    }

}



1 Like