Symfony2 - Manipulate request/response from the Kernel Exception Listener

后端 未结 2 1453
余生分开走
余生分开走 2021-02-06 07:22

I am building an administration panel for a website and I would like to change the view called when a 404 exception occurs but only for the admin application. <

相关标签:
2条回答
  • 2021-02-06 07:39

    For some reason, this worked:

    // get exception
    $exception = $event->getException();
    
    // get path
    $path = $event->getRequest()->getPathInfo();
    
    if ($exception->getStatusCode() == 404 && strpos($path, '/admin') === 0){
    
        $templating = $this->container->get('templating');
    
        $response = new Response($templating->render('CmtAdminBundle:Exception:error404.html.twig', array(
            'exception' => $exception
        )));
    
        $event->setResponse($response);
    }
    

    Which is basically what I was doing earlier with a different syntax...

    @dmirkitanov Anyway, thanks for your help !

    0 讨论(0)
  • 2021-02-06 07:47

    You could try this one:

    public function __construct(TwigEngine $templating)
    {
        $this->templating = $templating;
    }
    
    public function onKernelException(GetResponseForExceptionEvent $event)
    {
        static $handling;
    
        $exception = $event->getException();
    
        if (true === $handling) {
            return;
        }
        $handling = true;
    
        $code = $exception->getCode();
    
        if (0 !== strpos($event->getRequest()->getPathInfo(), '/admin') && 404 === $code) {
            $message = $this->templating->render('AcmeBundle:Default:error404new.html.twig', array());
            $response = new Response($message, $code);
            $event->setResponse($response);
        }
    
        $handling = false;
    }
    

    $templating variable can be passed in services.xml:

    <service id="acme.exception.listener" class="%acme.exception.listener.class%">
        <tag name="kernel.event_listener" event="kernel.exception" method="onKernelException" />
        <argument type="service" id="templating" />
    </service>
    
    0 讨论(0)
提交回复
热议问题