Created
June 23, 2015 21:21
-
-
Save zyphlar/e1089be4c0f0499ab08b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 } |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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