0
namespace etc...

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Bundle\TwigBundle\Controller\ExceptionController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\HttpKernel;
use Symfony\Component\HttpKernel\Exception\FlattenException;
use Symfony\Component\HttpKernel\Log\DebugLoggerInterface;
use Symfony\Component\HttpFoundation\Response;

class MyExceptionController extends ExceptionController
{
    public function showAction(Request $request, FlattenException $exception, DebugLoggerInterface $logger = null, $format = 'html')
    {


    }
}

在控制器内不执行任何操作会返回“未捕获的异常 'Symfony\Component\Routing\Exception\ResourceNotFoundException' in...”错误。不确定这是否正确,或者这是否是另一个问题。我希望它只是做通常的动作。

我只需要这样做,它就可以像访问 domain.com/page 一样显示指定的路线。

我试过这个:

   $httpKernel = $this->container->get('kernel');
   $response = $httpKernel->forward('AcmeMyBundle:Default:pageAction');
   $this->setResponse(new Response($response));

...但得到这个错误:

Call to a member function get() on a non-object in...
4

1 回答 1

3

您的代码看起来与我昨天所做的类似。我想获取所有 NotFoundHttpException 异常并尝试将它们转发到默认控制器。我通过这样的异常监听器实现了这一点:

<?php

namespace Acme\MyBundle\Listener;

use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;

class NotFoundHttpExceptionListener
{
    protected $container;

    public function setContainer($container)
    {
        $this->container = $container;
    }

    public function onKernelException(GetResponseForExceptionEvent $event)
    {
        $exception = $event->getException();
        if ($exception instanceof NotFoundHttpException) {
            $httpKernel = $this->container->get('http_kernel');

            $response = $httpKernel->forward(
                'AcmeMyBundle:Controller:action',
                array(
                    'uri'  => $_SERVER['REQUEST_URI'],
                )
            );

            $response->headers->set('X-Status-Code', '200');
            $event->setResponse($response);
            $event->stopPropagation();
        }
    }
}

请注意,如果您想返回除 404 之外的另一个状态代码,则 X-Status-Code 是必需的,因为 HttpKernel 中的 handleException 方法将使用它来设置最终状态代码并将其从标题部分中删除。

我的 services.yml 看起来像这样:

notfoundhttp.exception.listener:
  class: Acme\MyBundle\Listener\NotFoundHttpExceptionListener
  calls:
    - [ setContainer, [@service_container] ]
  tags:
    - { name: kernel.event_listener, event: kernel.exception, method: onKernelException }
于 2013-04-15T06:31:38.900 回答