1

I need to do one of two things (in priority order, but just need one of them).

All of this is to be done inside a function that runs as an Exception Event Listener (http://api.symfony.com/2.2/Symfony/Component/HttpKernel/Event/GetResponseForExceptionEvent.html).

Both below are totally easy inside a normal controller, but I can't see it possible inside an event listener function.

(1) Run a controller as normal and output as normal as though that route had been executed:

e.g. $event->runController('controllerName');

(2) render a template as normal using the same syntax as would inside a normal controller:

return $this->render('Bundle:Default:feedback.html.twig', array([template vars]));

1 Answer 1

1

take a look at symfony's default exception listener in Symfony\Component\HttpKernel\EventListener\ExceptionListener.

(1) running a controller can be realized this way:

    $request = new \Symfony\Component\HttpFoundation\Request();
    $request->setMethod('GET');
    [..]

    try {
        $response = $event->getKernel()->handle($request, HttpKernelInterface::SUB_REQUEST, true);
    } catch (\Exception $e) {
        return; // pass it to next exception listener this way 
    }

    $event->setResponse($response);

(2) rendering a template in exception listener

all you need to do is pass templating (engine) to the listener inside the service.yml

    services:
      foobar.exception_listener_service:
        class: %foobar.exception_listener_service.class%
        arguments:
          container: "@service_container"
        tags:
          - { name: kernel.event_listener, event: kernel.exception, method: onKernelException, priority: 255 }

inside the listener you can render templates as listed below

    $templating = $this->container->get('templating');
    $response = new Response($templating->render('foobar:Exception:error404.html.twig', array('exception' => $exception)));
    $event->setResponse($response);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.