Select Page

I wanted to be able to handle 404 , 500 errors etc. in my own way. The first step is to create your custom error404.html.twig template. The issue I was having was that I had a dynamic menu (amongst other things) that were then not available to the view.
Using the built in exception handler resulted in required variables not being available.

This meant building my own exception handler:
[cc lang=”php”]
namespace MyCo\MyBundle\Listener;

use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Bundle\TwigBundle\TwigEngine;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;

class MyErrorExceptionListener
{

private $container;

function __construct($container)
{
$this->container = $container;
}

public function onKernelException(GetResponseForExceptionEvent $event)
{
// We get the exception object from the received event
$exception = $event->getException();

if($exception->getStatusCode() == 404)
{

$response = new Response($templating->render(‘MyBundle:Exception:error404.html.twig’, array(
‘exception’ => $exception
)));

$event->setResponse($response);

}

}[/cc]
and then in your config.yml register the service:

 

core.exceptlistener:
class: %core.exceptlistener.class%
arguments: [@service_container]
tags:
– { name: kernel.event_listener, event: kernel.exception, method: onKernelException, priority: 200 }

making sure to pass any arguments you want into the service register.

You should then be able to pass any dependent variables in using something like:

$globalVars = $this->container->get(‘globalvars’);

%d bloggers like this: