How can I redirect to a specific page when the database connection failed with an error in Yii?

I do not want to see the Yii error message when the connection to the database fails. How can I redirect to a specific page when the connection to the database fails using the Yii schema? Thanks.

+6
source share
2 answers

To catch all CDbConnection errors, you need to enable the error handler in the config / main.php file

'components'=>array('errorHandler'=>array('errorAction'=>'site/error', ), ), 

Then in your controller (or an abstract base class for all your controllers) you need to define an action to perform the redirect.

 public function actionError() { if($error=Yii::app()->errorHandler->error) if ( CDbException == $error->type) { $this->redirect(array("site/error_message")); } // call the parent error handler, but something doesn't feel right about this: else parent::actionError(); } 

Alternatively, you can simply visualize your custom views:

 public function actionError() { if($error=Yii::app()->errorHandler->error) if ( CDbException == $error->type) { $this->render('error', $error); } } 

See Yii docs for more details.

+6
source

you can do something like:

 try { $connection=new CDbConnection($dsn,$username,$password); } catch(Exception $e) { $this->redirect(array('controller/action')); } 

you can also pass additional information via redirection, see here .

+1
source

Source: https://habr.com/ru/post/897022/


All Articles