<?php
namespace App\EventSubscriber;
use Doctrine\DBAL\Exception\UniqueConstraintViolationException;
use Psr\Log\LoggerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\Exception\ConflictHttpException;
use Symfony\Component\HttpKernel\KernelEvents;
class UniqueConstraintViolationExceptionSubscriber implements EventSubscriberInterface
{
public function __construct(
private LoggerInterface $logger,
)
{
}
public static function getSubscribedEvents(): array
{
return [
KernelEvents::EXCEPTION => 'onKernelException',
];
}
public function onKernelException(ExceptionEvent $event): void
{
$exception = $event->getThrowable();
if (!$exception instanceof UniqueConstraintViolationException) {
return;
}
$this->logger->warning(sprintf(
'Concurrent write detected (unique constraint violation) on "%s": %s',
$event->getRequest()->getPathInfo(),
$exception->getMessage(),
));
$event->setThrowable(new ConflictHttpException(
'This resource was modified concurrently, please try again.',
$exception,
));
}
}