src/EventListener/ExceptionListener.php line 17

Open in your IDE?
  1. <?php
  2. namespace App\EventListener;
  3. use Doctrine\DBAL\Exception\ForeignKeyConstraintViolationException;
  4. use Symfony\Component\HttpFoundation\RedirectResponse;
  5. use Symfony\Component\HttpFoundation\Session\Session;
  6. use Symfony\Component\HttpKernel\Event\ExceptionEvent;
  7. class ExceptionListener {
  8. private $session;
  9. public function __construct( Session $session) {
  10. $this->session = $session;
  11. }
  12. public function onKernelException( ExceptionEvent $event ) {
  13. $exception = $event->getThrowable();
  14. $exceptionMessage = $event->getThrowable()->getMessage();
  15. // Listen only on the expected exception
  16. if (!$exception instanceof ForeignKeyConstraintViolationException) {
  17. return;
  18. }
  19. // Case delete fails because some data are related to that foreign key
  20. if (strpos($exceptionMessage, 'Cannot delete or update a parent row: a foreign key constraint fails')) {
  21. // Add your user-friendly error message
  22. $this->session->getFlashBag()->add('error', 'Questo record non può essere eliminato perchè ha dei dati correlati.');
  23. $response = new RedirectResponse($event->getRequest()->getPathInfo());
  24. $event->setResponse($response);
  25. }
  26. }
  27. }