Wednesday, February 16, 2022

[FIXED] Symfony php Custom exception controller not working

Issue

I'm trying to create a custom exception controller in php Symfony 4. Essentially what I want to do is to have a default route that gets called when no other routes match.

I'm trying to follow the suggestions here: https://symfony.com/doc/current/controller/error_pages.html#custom-exception-controller

I've created the twig.yaml file inside configs>>pacakges:

twig:
    exception_controller: App\Controller\ExceptionController::showException

I've also created the ExceptionController class:

<?php
namespace  App\Controller;


use Symfony\Component\HttpFoundation\Response;

class ExceptionController
{

    public function showException()
    {
        $response = new Response();
        $response->setContent("Some random text");
        $response->headers->set('Content-Type', 'text/plain');
        $response->headers->set('Access-Control-Allow-Origin', '*');
        $response->setStatusCode(200);
        return $response;
    }
}

When I visit a url that does not exist I'm expecting to see the text "Some random text" but instead I get the default symfony not found page:

enter image description here

Any ideas what I might be doing wrong?


Solution

You mentioned that you created a twig.yaml under configs/packages.

Two things:

  1. This should be config, not configs
  2. twig.yaml should already exist, there is no need to create this file.

My suspicion is that if you created this file, you've created a file in the wrong place and Symfony is not picking up your configuration change. Instead, add your configuration change to the existing twig.yaml file under config/packages.

Once you add your custom exception_controller path to this existing (assumed default) twig.yaml it should look something like this:

twig:
    default_path: '%kernel.project_dir%/templates'
    debug: '%kernel.debug%'
    strict_variables: '%kernel.debug%'
    exception_controller: App\Controller\ExceptionController::showException

I tested this with a fresh install and it works as expected.

Hope this helps :)


Your method should be called showException and not endpoint as you defined in your twig.exception_controller configuration.



Answered By - Darragh Enright

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.