Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I redirect to a specific page when the database connection fails in Yii?

Tags:

php

yii

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

like image 901
user7300084 Avatar asked Sep 09 '11 21:09

user7300084


2 Answers

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

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

Then, within your controller (or an abstract base class for all your controllers) you need define an action to accomplish 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 just render 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.

like image 147
hobs Avatar answered Oct 17 '22 10:10

hobs


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 info with the redirect, see here.

like image 38
ldg Avatar answered Oct 17 '22 10:10

ldg