src/EventSubscriber/UniqueConstraintViolationExceptionSubscriber.php line 27

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use Doctrine\DBAL\Exception\UniqueConstraintViolationException;
  4. use Psr\Log\LoggerInterface;
  5. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  6. use Symfony\Component\HttpKernel\Event\ExceptionEvent;
  7. use Symfony\Component\HttpKernel\Exception\ConflictHttpException;
  8. use Symfony\Component\HttpKernel\KernelEvents;
  9. class UniqueConstraintViolationExceptionSubscriber implements EventSubscriberInterface
  10. {
  11. public function __construct(
  12. private LoggerInterface $logger,
  13. )
  14. {
  15. }
  16. public static function getSubscribedEvents(): array
  17. {
  18. return [
  19. KernelEvents::EXCEPTION => 'onKernelException',
  20. ];
  21. }
  22. public function onKernelException(ExceptionEvent $event): void
  23. {
  24. $exception = $event->getThrowable();
  25. if (!$exception instanceof UniqueConstraintViolationException) {
  26. return;
  27. }
  28. $this->logger->warning(sprintf(
  29. 'Concurrent write detected (unique constraint violation) on "%s": %s',
  30. $event->getRequest()->getPathInfo(),
  31. $exception->getMessage(),
  32. ));
  33. $event->setThrowable(new ConflictHttpException(
  34. 'This resource was modified concurrently, please try again.',
  35. $exception,
  36. ));
  37. }
  38. }