Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

I'm overriding the CREATE method with my own 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 is trying to be saved, in my case there is an "Integrity constraint violation" in my database.

What I would like is to handle that error and run my "catch", but I don't know how to "catch" that error, because Yii is "taking control" of that error and throw a 500 error as response.

How can I handle the "model save" errors ?

like image 591
FlamingMoe Avatar asked Jun 26 '15 09:06

FlamingMoe


1 Answers

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

like image 195
Tony Avatar answered Nov 15 '22 06:11

Tony