Implement a custom error controller in Symfony 4.4

3.3k Views Asked by At

What i have done:

I have created this custom controller cause I want to pass to the error pages some extra variables.

#Controller/CustomErrorControler.php
namespace App\Controller;

use App\Controller\Base\BaseController;
use Symfony\Component\ErrorHandler\Exception\FlattenException;
use Symfony\Component\HttpKernel\Log\DebugLoggerInterface;

class CustomErrorController extends BaseController
{

    public function show(FlattenException $exception, DebugLoggerInterface $logger = null)
    {
        return $this->getView('bundles/TwigBundle/Exception/error.html.twig', [
            "code" => $exception->getStatusCode(),
            "message" =>$exception->getStatusText()
        ]);
    }
}

and the enabled

#config/packages/framework.yaml
error_controller: App\Controller\CustomErrorController::show

I have followed the documentation directly. My problem is that I need, for non-production stages to get the default exception templates provided by the framework.

I have tried to extend Symfony\Component\HttpKernel\Controller\ErrorController but I'm getting errors for autowiring.

Maybe I should use Symfony\Component\ErrorHandler\ErrorRenderer\ErrorRendererInterface Any ideas how to implement this?

2

There are 2 best solutions below

0
On BEST ANSWER

Solved it by using different framework.yaml for Prod

0
On

If you want to use your custom controller only in production you can modify your config/packages/framework.yaml file by adding the when clause, like this:

when@prod:
    framework:
        error_controller: App\Controller\CustomErrorController::show

This will ensure that your custom error controller is only used in the production environment, while the default exception templates are used in other environments