PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, February 16, 2022

[FIXED] Symfony php Custom exception controller not working

 February 16, 2022     controller, php, routes, symfony, symfony4     No comments   

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
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

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

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing