Yii2 发生异常时显示错误

Yii2 show error when exception occurs

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

...
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 页面,我不知道如何让错误可见。请指出正确的方向。谢谢!

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

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) {
          ......