Handling 404 error in Symfony: Tutorial & Examples

Updated: January 13, 2024 By: Guest Contributor Post a comment

Overview

In this tutorial, we will go through the methods of handling 404 HTTP errors using Symfony, a robust PHP framework widely used for web application development. Being able to manage 404 errors effectively is important for improving user experience and is a best practice in web development.

404 Not Found Error

A 404 Not Found error occurs when a user tries to access a webpage that does not exist. This could be due to a mistyped URL, a deleted page, or a broken link. A proper 404 handling mechanism ensures that users are informed about the error in a user-friendly manner and are provided with options to navigate back to the working parts of your application.

Setting up a Symfony Project

Before we start handling 404 errors, we need a Symfony project. If you don’t have one, you can set it up using Composer, PHP’s dependency manager:

composer create-project symfony/skeleton my_project_name

Once you have your project setup, you can run it using the Symfony server:

cd my_project_name
symfony server:start

Handling 404 Errors in Symfony

Using Symfony’s Exception Controller

The simplest way to handle 404 errors in Symfony is by using the ExceptionController built into the TwigBundle. When Symfony encounters a 404 error, it throws an exception, which the ExceptionController handles to display an appropriate error page.

Custom Error Pages

To create custom error pages, you create templates in the templates/bundles/TwigBundle/Exception/ directory. For a 404 error, you would name the template error404.html.twig. Then, customize this template according to your application’s needs.

Configuration

Symfony allows you to configure error page templates based on the environment. For example, in the config/packages/twig.yaml you can define the path where Symfony looks for the error templates:

twig:
    debug: '%kernel.debug%'
    strict_variables: '%kernel.debug%'
    exception_controller: 'App\Controller\CustomExceptionController::showAction'

With this configuration, you inform Symfony to use your custom controller for rendering error pages.

Creating a Custom Exception Controller

If the default ExceptionController does not meet your needs, you may want to implement your custom exception controller. Here’s a guide on creating one:

Step 1: Creating the Controller

First, create your custom exception controller class in the src/Controller directory. Extend it from Symfony’s AbstractController or another base class that fits your needs. The controller should have an action method, such as showAction, that renders your custom error template:

namespace App\Controller;

use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;

class CustomExceptionController extends AbstractController
{
    public function showAction(HttpExceptionInterface $exception): Response
    {
        return new Response(
            $this->renderView('bundles/TwigBundle/Exception/error.html.twig', [
                'message' => 'Something went wrong.',
            ]),
            $exception->getStatusCode()
        );
    }
}

Step 2: Configuring the Controller Service

In your service configuration file, often located in config/services.yaml, you need to register your controller as a service:

services:
    App\Controller\CustomExceptionController:
        tags:
            - { name: 'controller.service_arguments' }

Testing Your 404 Error Page

Once you have configured your custom error page or controller, you should test it by intentionally accessing a non-existent URL in your application. You should see your custom 404 error page.

Logging 404 Errors

Logging errors can be crucial for maintenance and debugging. Symfony provides Monolog, a logging service that is easy to configure and use. By default, it logs errors, including 404s. However, make sure it’s configured correctly in your config/packages/prod/monolog.yaml to log errors in the production environment.

Advanced: Event Listeners

Creating an event listener or subscriber in Symfony to handle the kernel.exception event is a powerful way to manage exceptions like 404 Not Found errors with more control and complexity. Here’s how you can do it:

Step 1: Create the Event Listener Class

First, you need to create a class that will listen to the kernel.exception event.

// src/EventListener/ExceptionListener.php

namespace App\EventListener;

use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;

class ExceptionListener
{
    public function onKernelException(ExceptionEvent $event)
    {
        // Retrieve the exception object from the received event
        $exception = $event->getThrowable();

        // Create a custom response for specific exception types
        if ($exception instanceof HttpExceptionInterface && $exception->getStatusCode() == 404) {
            $response = new Response('Page not found', 404);
        } else {
            $response = new Response('An error occurred', 500);
        }

        // Set the response object on the event
        $event->setResponse($response);
    }
}

In this class, the onKernelException method checks the type of exception and sets a custom response accordingly.

Step 2: Register the Event Listener

Next, register your listener for the kernel.exception event in your services.yaml:

# config/services.yaml

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

This configuration ensures that your listener gets called whenever the kernel.exception event is triggered.

Using the Event Listener

With this setup, your application will use the ExceptionListener class to handle exceptions. When a 404 error occurs, it will return a ‘Page not found’ response. For other types of exceptions, it will return ‘An error occurred’.

Important Notes:

  • Make sure to test this listener thoroughly in different scenarios to ensure it behaves as expected.
  • This approach provides great flexibility but requires careful handling of different exception types to avoid unintended behavior.
  • Customizing the response further based on exception types or other criteria can enhance user experience in error scenarios.

Conclusion

In this tutorial, we’ve covered the basics of handling 404 errors in Symfony. We went through using default error pages, creating custom error pages, setting up a custom exception controller, logging, and advanced event handling. Proper error handling improves your application’s user experience and is a sign of a well-implemented web service. By understanding how to manage 404 errors in Symfony, you can ensure that your application behaves gracefully in the face of broken links or lost webpages.