Symfony 2.2 extend ExceptionController
Asked Answered
P

1

8

This question is related to the following change (part of Symfony 2.2 release):

Part 1

In pre-2.2 Symfony, I was overriding ExceptionController to display some custom error pages.

I did that via:

parameters:
       twig.exception_listener.controller: My\CustomBundle\CustomExceptionController::showAction

Now, after upgrading to 2.2, I can no longer do that, because an exception is thrown while generating an exception (no pun intended):

ExceptionController::__construct() must be an instance of Twig_Environment, none given, called in...

Since ExceptionController is a service now, how can I override that, and what do I need to change in my old code?

All I did in the custom class, is changed the template reference in showAction method:

$template = new TemplateReference('TwigBundle', 'Exception', $name, $format, 'twig');

Part 2

Since ExceptionController no longer extends ContainerAware, how do I get to the current container? Is it enough to implement ContainerAwareInterface?

Phantom answered 2/4, 2013 at 20:0 Comment(0)
M
12

You should change a couple of this:

  1. you need to inherit the ExceptionController in your custom Exception controller.
  2. you need to override the twig.controller.exception.class parameter. As you can see in the service file, it uses the twig.controller.exception.class parameter to identify the exception controller class. Now override it with your class:

    parameters:
        twig.controller.exception.class: My\CustomBundle\CustomExceptionController
    
  3. you need to edit the signature of the showAction to follow the new signature

    Since ExceptionController no longer extends ContainerAware, how do I get to the current container? Is it enough to implement ContainerAwareInterface?

No, services shouldn't never inject the container. You should inject the services you need in the constructor, as is done with the Twig_Environment service.

Inside your Exception controller, you get access to the $this->twig property for the twig service. And the new signature gets a $request parameter, to get the request. I don't think you need more. (you also get $this->debug)

Misdemean answered 2/4, 2013 at 20:40 Comment(4)
Thanks Wouter! What I was missing is the twig.controller.exception.class override. Works like a charm now.Phantom
Actually for the 2nd part of my question, in the previous implementation of ExceptionController, I was able to retrieve parameter from $this->container->getParameter(). How can I retrieve that same parameter in the new custom exception controller, now that it's a service? Is using $this->twig->getGlobals() would be the right way to go?Phantom
I found this tutorial useful too: knpuniversity.com/screencast/symfony2-ep3/error-pagesRastus
I'm getting the same error, I'm following this using Symfony 3.2.0-DEV and I'm already inheriting from ExceptionController.. How can I solve?Lawson

© 2022 - 2024 — McMap. All rights reserved.