php - Symfony2 : Redirect user to index page when page not found or 404 errors thrown

标签 php symfony symfony-2.4

当 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/

相关文章:

Symfony:如何避免自定义表单类型自动包装在 div 中?

php - Symfony2 + 存储过程 ||如何获取结果?

php - 基于PHP代码设置单选按钮的值

php - PDO 以列表形式从 mysql 数据库返回数据

php - Symfony2 自定义 Twig 扩展 - 未找到类

Symfony 2 : Accessing a firewalled route with two separate providers

php - 在 Symfony 服务中获取路由名称

php - HTML 修改的 jQuery 监听器

php - 搜索引擎优化谷歌没有注意到我的网站