当 symfony2 中出现找不到页面错误时,我想将用户重定向到特定页面。
用于自定义我创建的错误页面消息
app\Resources\TwigBundle\views\Exception\error404.html.twing
但现在我想将用户重定向到特定页面。我怎样才能做到这一点?
谢谢
最佳答案
您想要创建一个 event listener它监听内核在遇到异常时调度的 kernel.exception
事件。
然后,您将在监听器内部检查异常是否是 NotFoundHttpException
的实例,如果是,则重定向到您选择的页面。
这是一个例子:
<?php
// src/Acme/DemoBundle/EventListener/AcmeExceptionListener.php
namespace Acme\DemoBundle\EventListener;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
class AcmeExceptionListener
{
public function onKernelException(GetResponseForExceptionEvent $event)
{
// You get the exception object from the received event
$exception = $event->getException();
if ($event->getException() instanceof NotFoundHttpException) {
$response = new RedirectResponse($url);
$event->setResponse($response);
}
}
}
显然,您需要注册事件监听器。它只是一项服务,因此您只需照常注册即可。
# app/config/config.yml
services:
kernel.listener.your_listener_name:
class: Acme\DemoBundle\EventListener\AcmeExceptionListener
tags:
- { name: kernel.event_listener, event: kernel.exception, method: onKernelException }
关于php - Symfony2 : Redirect user to index page when page not found or 404 errors thrown,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23216925/