Search code examples
phpexceptionyiiyii-components

Adding custom error message once Exception called within a loop


I have the following block of code within a while loop (while loop generated from a csv) - if for whatever something goes wrong then ALL transactions are rolled back. This seems to work fine, i'd like to be able to 'log' each row/iteration within this loop where an Exception takes place to enable to display a flash message that will say something like the following below.. is this possible?

"You have a problem on Line 12."
"You have a problem on Line 17."

Transaction Code

try {
  if ($model->save()) {
      // continue with whatever logic you have
      $transaction->commit();
  }else{
      throw new Exception('Could not save model');
  }
}catch(Exception $e){
   $transaction->rollback();
}

Solution

  • you can always use addError() function of models to add a custom message to and attribute, and after that something went wrong, you can check the model for error messages with getErrors().