Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
services:
my_custom_exception_listener:
class: Acme\YourBundle\Listener\MyCustomExceptionListener
arguments: ['@templating', '@logger']
tags:
- { name: kernel.event_listener, event: kernel.exception, method: onKernelException, priority: 200 }
<?php
namespace Acme\YourBundle\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\Component\Routing\Exception\RouteNotFoundException;
use Symfony\Bundle\TwigBundle\TwigEngine;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Bridge\Monolog\Logger;
class MyCustomExceptionListener
{
private $templating;
private $logger;
function __construct(TwigEngine $templating, Logger $logger)
{
$this->templating = $templating;
$this->logger = $logger;
}
public function onKernelException(GetResponseForExceptionEvent $event)
{
// We get the exception object from the received event
$exception = $event->getException();
if($exception instanceof \Twig_Error_Runtime)
{
// if getPrevious doesn't work, maybe try __call(string $method, array $arguments)
if($exception->getPrevious() instanceof RouteNotFoundException){
$this->logger->error($exception->getRawMessage());
$response = new Response($this->templating->render('TwigBundle:Exception:my_custom_error_page.html.twig', array(
'status_text' => $exception->getRawMessage(),
'status_code' => $exception->getTemplateFile()." at ".$exception->getTemplateLine(),
'exception' => $exception
)), 404);
$event->setResponse($response);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment