简体   繁体   中英

How can I redirect to a specific page when the database connection fails in 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.

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM