我想将用户重定向到特定页面。当找不到页面时,symfony2中出现错误。
为了自定义错误页面消息,我创建了
app'Resources'TwigBundle'views'Exception'error404.html.twing
但现在我想将用户重定向到特定的页面。我该怎么做?
感谢
您希望创建一个事件侦听器,用于侦听内核在遇到异常时调度的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 }
必须使用.htaccess。请看这个。