在Yii中,当数据库连接失败时,如何重定向到特定的页面?


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

我不希望在数据库连接失败时看到Yii错误消息。如何重定向到一个特定的页面时,数据库连接失败与Yii框架?谢谢。

要捕获所有 CDbConnection错误,您需要在config/main.php

中启用错误处理程序
'components'=>array('errorHandler'=>array('errorAction'=>'site/error', ), ),

然后,在你的控制器(或所有控制器的抽象基类)中,你需要定义一个动作来完成重定向。

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(); }

或者你可以直接渲染你的自定义视图:

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

详情请参阅Yii文档

你可以这样做:

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

你也可以通过重定向传递额外的信息,见这里