<?php
namespace App\EventListener;
use Doctrine\DBAL\Exception\ForeignKeyConstraintViolationException;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
class ExceptionListener {
private $session;
public function __construct( Session $session) {
$this->session = $session;
}
public function onKernelException( ExceptionEvent $event ) {
$exception = $event->getThrowable();
$exceptionMessage = $event->getThrowable()->getMessage();
// Listen only on the expected exception
if (!$exception instanceof ForeignKeyConstraintViolationException) {
return;
}
// Case delete fails because some data are related to that foreign key
if (strpos($exceptionMessage, 'Cannot delete or update a parent row: a foreign key constraint fails')) {
// Add your user-friendly error message
$this->session->getFlashBag()->add('error', 'Questo record non può essere eliminato perchè ha dei dati correlati.');
$response = new RedirectResponse($event->getRequest()->getPathInfo());
$event->setResponse($response);
}
}
}