We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

about transaction rollback

Do I need to throw an exception after transation rollback in try catch block? Thx



98.9k

That depends on the type of strategy you are using to handle the transactions.



29.1k

the code is something like:

try {
   ...
   $a->setTransaction($t);
   $b->setTransaction($t);

   if (!$a->save()) {
      $t->rollback();
      /*
      Do I need add return or throw new Exception(); here to exit current follow and goto finally block?
      */
   }

   if (!$b->save()) {
      $t->rollback();
      /*And here*/
   }
   $t->commit();
}
catch (Exception $e) {
   ...
}
finally {
   ...
}


98.9k
Accepted
answer

Yes, you need to throw an exception after $t->rollback();

According to the docs if you use TransactionManager you can catch Phalcon\Mvc\Model\Transaction\Failed $e exception:

<?php

try {
   use Phalcon\Mvc\Model\Transaction\Manager as TransactionManager;

   $transactionManager = new TransactionManager();

   $transaction = $transactionManager->get();

   $robot = new Robots();

   $robot->setTransaction($transaction);

   $robot->name       = "WALL·E";
   $robot->created_at = date("Y-m-d");

   if ($robot->save() === false){
       $transaction->rollback("Can't save robot");
   }

   $robotPart = new RobotParts();

   $robotPart->setTransaction($transaction);

   $robotPart->type = "head";

   if ($robotPart->save() === false) {
       $transaction->rollback("Can't save robot part");
   }

   $transaction->commit();
} catch (Phalcon\Mvc\Model\Transaction\Failed $e) {
   echo "Failed, reason: ", $e->getMessage();
}

Source: https://docs.phalcon.io/en/3.2/api/Phalcon_Mvc_Model_Transaction_Manager