发生异常时,Yii2显示错误

时间:2016-01-28 19:26:19

标签: exception-handling transactions yii2 model-validation

我的控制器中有这个代码:

...
if (Model::validateMultiple($ttepk)) {
    $transaction = \Yii::$app->db->beginTransaction();
    try {
        foreach ($ttepk as $ttep) {
            $ttep->save(false);
            if (!$ttep->assignPs()) {
                throw new UserException('assignPs failed');
            }
        }
        $transaction->commit();
        return $this->redirect(['index']);
    } catch (Exception $ex) {
        $transaction->rollBack();
        throw $ex;
    }
}
...
模特中的

...
public function assignPs() {
    foreach (...) {
        $ttepetk[...] = new Ttepet;
        $ttepetk[...]->ttepId = $this->id;
        ... // set other attributes
        }
    }

    if (Model::validateMultiple($ttepetk)) {
        foreach ($ttepetk as $ttepet) {
            $ttepet->save(false);
        }
        return true;
    } else {
        return false;
    }
}
...

一切正常(如果任何模型未通过验证,则不会发生插入),除了我希望看到确切的错误,确切地说是Ttep(每个Ttep是模型)和Ttepet(Ttep: Ttepet = 1:N)发生了错误,那是什么。现在我只看到了Exeption页面,而且我不知道如何使错误可见。请指出正确的方向。谢谢!

1 个答案:

答案 0 :(得分:0)

您可以逐个验证逐个验证的每个模型并在发生时获取错误...

if (Model::validateMultiple($ttepetk)) {
    foreach ($ttepetk as $ttepet) {
        $ttepet->save(false);
    }
    return true;
} else {
  foreach($ttepetk as $model){
      if ($model->validate()) {
        // all inputs are valid
    } else {
      // validation failed: $errors is an array containing error messages
      $errors = $model->errors;
    }
  }
    return $errors;  
}

你可以通过这种方式获得错误

  $myErrorResult = $ttep->assignPs();
  if (!$myErrorResult) {
          ......