How to catch DB exception when overriding actionCreate in Yii2 RESTful API?

I am using the YII2 RESTful API implementation. This is a good start: http://budiirawan.com/setup-restful-api-yii2/

I am overriding the CREATE method with my action:

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

    }

      

The problem is when the model tries to be saved, in my case there is an "integrity constraint violation" in my database.

I would like to handle this error and run my catch, but I don’t know how to “catch” this error because Yii “takes control” of this error and throws 500 errors as a response.

How can I handle "save model" errors?

+3


source to share


1 answer


Yii2 doesn't have CDbException

. To catch all db related exceptions you need to catch(\yii\db\Exception $e){...}

and catch any other exceptionscatch(\Exception $e){...}

You have two exceptions, but they do the same, so just



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

      

\Exception

is the base php exception class from which all yii2 exceptions are inherited

+5


source







All Articles