Home > Enterprise >  Symfony: redirecting to homepage after encountering an error
Symfony: redirecting to homepage after encountering an error

Time:12-20

I've recently started learning Symfony, and I've been trying to make an app that will redirect user to the homepage after encountering an error (For the sake of the question, it can be error 404) However, I had problems with finding a way to do so.

Before, I used TwigErrorRenderer as described in Symfony documentation to handle my errors, but it only explains how to redirect to new error pages created by myself. Could somebody help me with this issue?

CodePudding user response:

It is generally not a good idea to do this, because you want to tell the user that their request was not processed due to an error, or that they accessed non-existing page.

But if you really want to, you can achieve it with this Event Listener.

// src/EventListener/ExceptionListener.php
<?php

declare(strict_types=1);

namespace App\EventListener;

use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\Routing\RouterInterface;

final class ExceptionListener
{
    private RouterInterface $router;

    public function __construct(RouterInterface $router)
    {
        $this->router = $router;
    }

    public function onKernelException(ExceptionEvent $event): void
    {
        // You should log the exception via Logger
        // You can access exception object via $event->getThrowable();

        $homepageRoute = $this->router->generate('homepage', [], RouterInterface::ABSOLUTE_URL);
        $response = new RedirectResponse($homepageRoute);

        $event->setResponse($response);
    }
}

You also need to register the Event Listener in your services.yaml.

services:
    App\EventListener\ExceptionListener:
        tags:
            - { name: kernel.event_listener, event: kernel.exception }

Please note the following:

  1. The Event Listener assumes that your Homepage route is called homepage;
  2. you really should log the exception or you will lose logs about all of them;
  3. as stated at the top of this answer, this is not a good approach to deal with exceptions.
  • Related