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'”错误。不确定这是否正确,或者这是否是另一个问题。我希望它只是做通常的行动。
我只需要这样做,这样就可以像访问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...
答案 0 :(得分: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 }