Nisarg
Nisarg

Reputation: 3282

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

I want to redirect user to particular page When page not found error comes in symfony2.

For customization of error page message I created

app\Resources\TwigBundle\views\Exception\error404.html.twing

But now I want to redirect user to particular page. How can I do that?

Thanks

Upvotes: 2

Views: 1802

Answers (2)

Léo Lam
Léo Lam

Reputation: 4139

You would want to create an event listener that listens for the kernel.exception event the kernel dispatches when it encounters an exception.

Then, you would check inside the listener if the exception is an instance of NotFoundHttpException, and if it is, redirect to the page of your choice.

Here's an exemple:

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

Obviously, you'll need to register the event listener. It is just a service, so you just need to register it as usual.

# 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 }

Upvotes: 2

train_fox
train_fox

Reputation: 1537

You must use .htaccess for this. Please see this.

Upvotes: 0

Related Questions