如何在Yii2 RESTful API中覆盖actionCreate时捕获数据库异常?

时间:2015-06-26 09:14:22

标签: rest yii2 yii2-advanced-app

我正在使用Yii2 RESTful API实现。 这是一个好的开始:http://budiirawan.com/setup-restful-api-yii2/

我用我自己的行动覆盖了CREATE方法:

    public function actionCreate(){
        $params = $_REQUEST;    
        if (!empty($params["name"]) && !empty($params["code"])) {
            $model = new $this->modelClass;
            foreach ($params as $key => $value) {
                if (!$model->hasAttribute($key)) {
                    throw new \yii\web\HttpException(400, 'Invalid attribute:' . $key);
                }
            }

            $model->attributes=$params;
            try {
                $model->save();
            } catch (CDbException $ex) {
                // ... NEVER REACH THIS POINT :-(
                throw new \yii\web\HttpException(405, 'Error saving model');
            } catch (Exception $ex) {
                // ... NEVER REACH THIS POINT :-(
                throw new \yii\web\HttpException(405, 'Error saving model');
            }

        } else {
            throw new \yii\web\HttpException(400, 'No data input');
        }

    }

问题是当模型试图保存时,在我的情况下存在"完整性约束违规"在我的数据库中。

我想要的是处理这个错误并运行我的" catch"但我不知道如何捕获"这个错误,因为Yii是"控制"该错误并将500错误作为响应。

我如何处理"模型保存"错误?

1 个答案:

答案 0 :(得分:5)

Yii2 does not have CDbException. To catch all db related exceptions you need to catch(\yii\db\Exception $e){...} and to catch any other exceptions catch(\Exception $e){...}

You are catching two exceptions but they do the same thing so just

catch(\Exception $e){ 
    throw new \yii\web\HttpException(405, 'Error saving model'); 
}

\Exception is basic php exception class from which all yii2 exceptions inherited