且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

symfony2:挂钩 NotFoundHttpException 以进行重定向

更新时间:2021-10-16 22:14:50

正如您从 this cookbook page,每当抛出异常时都会触发kernel.exception"事件.我不知道 NotFoundHttpException 有特定事件,但我建议为所有异常创建自己的侦听器服务,然后在服务中检查异常类型并添加自定义逻辑.

As you can see from this cookbook page, a "kernel.exception" event is fired whenever an exception is thrown. I'm not aware of there being a specific event for a NotFoundHttpException but I'd suggest creating your own listener service for all exceptions and then checking within the service for the type of exception and adding your custom logic.

(注意:我还没有测试过这个,但它至少应该让你知道如何实现这一点.)

(Note: I haven't tested this, but it should at least give you an idea of how this can be achieved.)

配置

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()));
            }
        }
    }
}