如何在Yii 2.0中显示自定义错误页面而不是外键错误

时间:2015-07-06 05:11:01

标签: php mysql yii2

收到完整性约束违规 - yii \ db \ IntegrityException删除行而不删除外键表中的行时出错。

我如何显示自定义错误页面而不是完整性约束违规 - yii \ db \ IntegrityException错误Yii 2

我如何在Yii 2.0中捕获并抛出异常

Image

1 个答案:

答案 0 :(得分:0)

这实际上不是你问过的答案,但我在Yii1中定制了错误处理程序,并希望它在Yii2中具有相同的行为。您可以在config / main.php上将其更改为:

 'errorHandler' => [
            'errorAction' => 'site/error' // To error/errorHandler
  ],

Controller Class错误有以下几行。你可以根据需要改变它。

class ErrorController extends CController {

    public $layout = '//layouts/column1';
    /**
     * This is the action to handle external exceptions.
     */
    public function actionErrorHandler() {
        if ($error = Yii::app()->errorHandler->error) {
            if ('CDbException' != $error['type']) {
                if (Yii::app()->request->isAjaxRequest)
                    echo $error['message'];
                else
                    $this->commonError($error);
            }else if ('CDbException' == $error['type']) {
                if (Yii::app()->request->isAjaxRequest)
                    echo $error['message'] = 'The system is unable to resolve the database error !';
                else
                    $this->databaseError($error);
            }
        }
    }

    /**
     * 
     * @param type array $error
     * @access : Internal, type private
     * @throws: Http exception.
     */
    private function commonError($error) {
        $this->render('code_error', $error);
    }

    /**
     * 
     * @param type array $error
     * @throws Exception
     */
    private function databaseError($error) {
        if (empty($error)) {
            $error['code'] = '404';
            $error['message'] = 'Unknown error !';
            $this->render('code_error', $error);
            Yii::app()->end(0, true);
        }

        $error['message'] = 'The system is unable to resolve the database error !';
        $this->render('database_error', $error);
    }

}