Tharunkumar
Tharunkumar

Reputation: 190

The EntityManager is closed,Doctrine\\ORM\\ORMException

I am having the below error when trying to insert the data by try cache method

This is my try catch function

$cardid = new CarddetailsId($uuidGenerator->generate());
$cardnumber = self::getCardNumber(); //this is generated random numbers
$cardexistencetype = ($key == "giftCardSchemeData") ? "Physical" : "E-Card" ;
$otherdata = array('cardnumber' => $cardnumber, 'cardexistencetype' => $cardexistencetype, 'isgiftcard' => true , 'giftcardamount' => $preload['value'], 'expirymonths' => $preload['expiryMonths'], 'isloyaltycard' => false, 'loyaltypoints' => null, 'pinnumber' => 4627);
$output = $otherdata;

try {
     $commandBus->dispatch(
         new CreateCarddetails($cardid, $output)
     );
  }
catch (UniqueConstraintViolationException $e) {
    var_dump($e);
   self::generateCardFunctionForErrorException($cardid, $output, $commandBus);
 }

Card numbers is unique so I have called another function and reinsert the data

public function generateCardFunctionForErrorException($cardid, $data, $commandBus) {
            $cardnumber = self::getCardNumber();
            $data['cardnumber'] = $cardnumber;
            try {
              $commandBus->dispatch(
                  new CreateCarddetails($cardid, $data)
              );
            }
            catch (UniqueConstraintViolationException $e) {
                 var_dump($e);
                self::generateCardFunctionForErrorException($cardid, $data, $commandBus);
            }
          }

CreateCarddetailsis called the command and initiate the repository function Below is my repository function code

public function save(Carddetails $carddetails)
    {
        $this->getEntityManager()->persist($carddetails);
        $this->getEntityManager()->flush();
    }

My command handler function is

public function handleCreateCarddetails(CreateCarddetails $command)
    {
        $carddetails = new Carddetails($command->getCarddetailsId(), $command->getCarddetailsData());
        $this->carddetailsRepository->save($carddetails);
    }

Upvotes: 1

Views: 3519

Answers (1)

svgrafov
svgrafov

Reputation: 2014

Check for existence of Carddetails entity before saving new one with same value for your field with that UniqueConstraint.

For example, assuming that you have duplicate ID error:

public function handleCreateCarddetails(CreateCarddetails $command)
{
    $existingDetails = $this->carddetailsRepository->find($command->getCarddetailsId());
    if (!$existingDetails){
        $carddetails = new Carddetails($command->getCarddetailsId(), $command->getCarddetailsData());
        $this->carddetailsRepository->save($carddetails);
    } else {
        throw new \Exception('Already have Details with this ID');
    }
}

Upvotes: 0

Related Questions