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 ?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With