title: How to catch DB exception when overriding actionCreate in Yii2 RESTful API?
body: <p>I'm using the Yii2 RESTful API implementation.
  This is a good start: <a href="http://budiirawan.com/setup-restful-api-yii2/" rel="noreferrer">http://budiirawan.com/setup-restful-api-yii2/</a></p>
  
  <p>I'm overriding the CREATE method with my own action:</p>
  
  <pre><code>    public function actionCreate(){
          $params = $_REQUEST;    
          if (!empty($params["name"]) &amp;&amp; !empty($params["code"])) {
              $model = new $this-&gt;modelClass;
              foreach ($params as $key =&gt; $value) {
                  if (!$model-&gt;hasAttribute($key)) {
                      throw new \yii\web\HttpException(400, 'Invalid attribute:' . $key);
                  }
              }
  
              $model-&gt;attributes=$params;
              try {
                  $model-&gt;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');
          }
  
      }
  </code></pre>
  
  <p>The problem is when the model is trying to be saved, in my case there is an "Integrity constraint violation" in my database.</p>
  
  <p>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.</p>
  
  <p>How can I handle the "model save" errors ?</p>