Override Default Error Controller in Symfony 7

Override Default Error Controller in Symfony 7

Symfony simplifies web application development with its robust set of features. One critical aspect of any web application is error handling, ensuring a graceful response when unexpected issues occur. Symfony provides a default error controller for this purpose, but in some cases, you may want to customize the error handling process to better suit the application's needs. This tutorial explains how to override the default error controller in Symfony 7.

The error_controller option in the framework.yaml file can be used to define the controller which will be called when an exception is thrown anywhere in the application.

config/packages/framework.yaml

framework:
    # ...
    error_controller: App\Controller\ErrorController::show

Once the option is set, create the custom error controller which accepts exception parameter of Throwable class. This controller will be triggered by the ErrorListener class, which listens for the kernel.exception event.

src/Controller/ErrorController.php

<?php

namespace App\Controller;

use Symfony\Component\HttpFoundation\Response;
use Throwable;

class ErrorController
{
    public function show(Throwable $exception): Response
    {
        return new Response($exception->getMessage());
    }
}

Leave a Comment

Cancel reply

Your email address will not be published.