rest - How to catch DB exception when overriding actionCreate in Yii2 RESTful API? -
i'm using yii2 restful api implementation. start: http://budiirawan.com/setup-restful-api-yii2/
i'm overriding create method own action:
public function actioncreate(){ $params = $_request; if (!empty($params["name"]) && !empty($params["code"])) { $model = new $this->modelclass; foreach ($params $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 point :-( throw new \yii\web\httpexception(405, 'error saving model'); } catch (exception $ex) { // ... never reach point :-( throw new \yii\web\httpexception(405, 'error saving model'); } } else { throw new \yii\web\httpexception(400, 'no data input'); } }
the problem when model trying saved, in case there "integrity constraint violation" in database.
what handle error , run "catch", don't know how "catch" error, because yii "taking control" of error , throw 500 error response.
how can handle "model save" errors ?
yii2 not have cdbexception
. catch db related exceptions need catch(\yii\db\exception $e){...}
, catch other exceptions catch(\exception $e){...}
you catching 2 exceptions same thing
catch(\exception $e){ throw new \yii\web\httpexception(405, 'error saving model'); }
\exception
basic php exception class yii2 exceptions inherited
Comments
Post a Comment