Configure route 403 error page in symfony 2.0

I want to customize error pages in Symfony 2.0

I know this is done by overwriting the layouts in app/Resources/TwigBundle/views/Exception/* , but I want to have different error pages for different routes.

I want one for the backend and one for the interface.

How can i achieve this?

+4
source share
2 answers

What you need to do is not too difficult. Symfony lets you explicitly specify which controller handles your exceptions. So in your config.yml you can specify an exception controller in your branch setup:

since symfony 2.2

 twig: exception_controller: my.twig.controller.exception:showAction services: my.twig.controller.exception: class: AcmeDemoBundle\Controller\ExceptionController arguments: [@twig, %kernel.debug%] 

before Symfony 2.1:

 twig: exception_controller: AcmeDemoBundle\Controller\ExceptionController::showAction 

Then you can create a custom showAction that displays a custom error page based on the route:

 <?php namespace AcmeDemoBundle\Controller; use Symfony\Component\HttpKernel\Exception\FlattenException; use Symfony\Component\HttpKernel\Log\DebugLoggerInterface; use Symfony\Component\HttpFoundation\Response; use Symfony\Bundle\TwigBundle\Controller\ExceptionController as BaseExceptionController; class ExceptionController extends BaseExceptionController { public function showAction(FlattenException $exception, DebugLoggerInterface $logger = null, $format = 'html') { if ($this->container->get('request')->get('_route') == "abcRoute") { $appTemplate = "backend"; } else { $appTemplate = "frontend"; } $template = $this->container->get('kernel')->isDebug() ? 'exception' : 'error'; $code = $exception->getStatusCode(); return $this->container->get('templating')->renderResponse( 'AcmeDemoBundle:Exception:' . $appTemplate . '_' . $template . '.html.twig', array( 'status_code' => $code, 'status_text' => Response::$statusTexts[$code], 'exception' => $exception, 'logger' => null, 'currentContent' => '', ) ); } } 

Obviously, you should probably set up an if statement where it checks the current route according to your needs, but that should do it.

You might want to add code that defaults to regular Twig error pages if you do not have a specific error template. For more information, check out the code in

 Symfony\Bundle\TwigBundle\Controller\ExceptionController 

and

 Symfony\Component\HttpKernel\EventListener\ExceptionListener 
+10
source

I use arguments: ["@twig", "%kernel.debug%"] instead of arguments: [@twig, %kernel.debug%]

0
source

All Articles