Hello everyone!

We have been investing plenty of personal time and energy for many years to share our knowledge with you all. However, we now need your help to keep this blog running. All you have to do is just click one of the adverts on the site, otherwise it will sadly be taken down due to hosting etc. costs. Thank you.

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);
}
}
}