从这个食谱页面可以看出,只要抛出异常,就会触发“kernel.exception”事件。我不知道 NotFoundHttpException 存在特定事件,但我建议为所有异常创建自己的侦听器服务,然后在服务中检查异常类型并添加自定义逻辑。
(注意:我没有对此进行测试,但它至少应该让您了解如何实现这一点。)
配置
acme.exception_listener:
class: Acme\Bundle\AcmeBundle\Listener\RedirectExceptionListener
arguments: [@doctrine.orm.entity_manager, @logger]
tags:
- { name: kernel.event_listener, event: kernel.exception, method: checkRedirect }
监听服务
namespace Acme\Bundle\AcmeBundle\Listener;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\Log\LoggerInterface;
use Doctrine\ORM\EntityManager;
class RedirectExceptionListener
{
/**
* @var \Doctrine\ORM\EntityManager
*/
protected $em;
protected $logger;
function __construct(EntityManager $em, LoggerInterface $logger)
{
$this->em = $em;
$this->logger = $logger;
}
/**
* @param \Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent $event
*/
public function checkRedirect(GetResponseForExceptionEvent $event)
{
$exception = $event->getException();
if ($exception instanceof NotFoundHttpException) {
// Look for a redirect based on requested URI
// e.g....
$uri = $event->getRequest()->getUri();
$redirect = $this->em->getRepository('AcmeBundle:Redirect')->findByUri($uri);
if (!is_null($redirect)) {
$event->setResponse(new RedirectResponse($redirect->getUri()));
}
}
}
}