Example below redirects user to a certain route when 404 NotFoundHttpException error occurs. It is done with onKernelException event listener and RedirectResponse() class.


Listeners.yml


services:
application_backend.event_listener.kernel_exception:
class: Application\BackendBundle\EventListener\KernelExceptionListener
arguments: [@router]
tags:
- { name: kernel.event_listener, event: kernel.exception, method: onKernelException }

KernelExceptionListener.php


If HTTP 404 Not Found error occurs anywhere in your application, we get redirected to the home page.


namespace Application\BackendBundle\EventListener;

use Symfony\Bundle\FrameworkBundle\Routing\Router;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

class KernelExceptionListener
{
private $router;
private $redirectRouter = 'application_frontend_default_index';

public function __construct(Router $router)
{
$this->router = $router;
}

public function onKernelException(GetResponseForExceptionEvent $event)
{
$exception = $event->getException();

if ($exception instanceof NotFoundHttpException) {
if ($event->getRequest()->get('_route') == $this->redirectRouter) {
return;
}

$url = $this->router->generate($this->redirectRouter);
$response = new RedirectResponse($url);
$event->setResponse($response);
}
}
}