R
R
Roma Antonyuk2017-05-05 14:49:01
Yii
Roma Antonyuk, 2017-05-05 14:49:01

How to make a redirect to another action in case of an error?

you need to make a redirect for any error on site / coming-soon, who can help the thread?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Valery, 2017-05-05
@smilik96

In the SiteController, provided that the error handler is set to site/error

public function actions()
    {
        return [
            'error' => [
                // изменяем класс обработчика ошибки
                'class' => 'frontend\components\ErrorAction',
            ],
        ];
    }

Next, we create the action itself:
<?php
namespace frontend\components ;
   
use Yii;
use yii\helpers\Url ;

class ErrorAction extends \yii\web\ErrorAction {
    public function run()
    {
        if (($exception = Yii::$app->getErrorHandler()->exception) === null) {
            $exception = new HttpException(404, Yii::t('yii', 'Page not found.'));
        }
        if ($exception instanceof HttpException) {
            $code = $exception->statusCode;
        } else {
            $code = $exception->getCode();
        }
        if ($exception instanceof Exception) {
            $name = $exception->getName();
        } else {
            $name = $this->defaultName ?: Yii::t('yii', 'Error');
        }
        if ($code) {
            $name .= " (#$code)";
        }

        if ($exception instanceof UserException) {
            $message = $exception->getMessage();
        } else {
            $message = $this->defaultMessage ?: Yii::t('yii', 'An internal server error occurred.');
        }

        if (Yii::$app->getRequest()->getIsAjax()) {
            return "$name: $message";
        } else {
            // !!!!!!!!!!!!!!!!!!!!!!! в случае необходимости редиректить один из статусо ошибки - подойдет такой вариант. В случае редиректа ВСЕХ ошибок - нужно убрать все условия и оставить лишь реирект
            if( $exception->statusCode == 404 ){
                Yii::$app->getResponse()->redirect( Url::home(true), 301 )->send();
                return;
            }else{
                return $this->controller->render($this->view ?: $this->id, [
                    'name' => $name,
                    'message' => $message,
                    'exception' => $exception,
                ]);
            }
        }
    }}

M
Maxim Timofeev, 2017-05-05
@webinar

www.yiiframework.com/doc-2.0/guide-runtime-handlin...

'components' => [
        'errorHandler' => [
            'errorAction' => 'site/coming-soon',
        ],
    ]

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question