尝试通过try cache method
插入数据时出现以下错误这是我的尝试捕捉功能
$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);
}
卡号是唯一的,因此我调用了另一个函数并重新插入数据
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调用该命令并启动存储库功能 下面是我的存储库功能代码
public function save(Carddetails $carddetails)
{
$this->getEntityManager()->persist($carddetails);
$this->getEntityManager()->flush();
}
我的命令处理函数是
public function handleCreateCarddetails(CreateCarddetails $command)
{
$carddetails = new Carddetails($command->getCarddetailsId(), $command->getCarddetailsData());
$this->carddetailsRepository->save($carddetails);
}
答案 0 :(得分:0)
检查Carddetails
实体是否存在,然后使用UniqueConstraint
为您的字段保存具有相同值的新实体。
例如,假设您有重复的ID错误:
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');
}
}