Michael Millar
Michael Millar

Reputation: 1614

How to avoid showing the stack trace in Symfony2 while on production?

When a user without the necessary role tries to access a page that requires a higher token, I rightfully get

AccessDeniedHttpException: Token does not have the required roles

But that is followed by the whole stack trace including the file path. E.g.

'file' => string '/var/www/myApp/vendor/jms/security-extra-bundle/JMS/SecurityExtraBundle/Security/Authorization/Interception/MethodSecurityInterceptor.php'

How do I remove the debugging information?

I've made sure I am on prod (app.php) and that

$kernel = new AppKernel('prod', false);

Update

To complete the solution based on Robert's answer, I had to tweak the yml syntax to include a dash

services:
    core.exceptlistener:
        class:  UserBundle\Listener\ExceptionListener
        arguments: ['@service_container', '@templating']
        tags:
            - { name: kernel.event_listener, event: kernel.exception, method: onKernelException }

And then create the twig file at the location specified in onKernelException, ensuring that the file inherited the base twig for the rest of my project

Upvotes: 0

Views: 1018

Answers (1)

Robert
Robert

Reputation: 3483

REG: To avoid stack trace you can use Event Listener

Listener Class

<?php
namespace UserBundle\Listener;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Twig\Template;

/**
 * Created by PhpStorm.
 * User: robert
 * Date: 20/8/17
 * Time: 2:26 PM
 */
class ExceptionListener
{
    /**
     *
     * @var ContainerInterface
     */
    private $container;

    function __construct($container) {
        $this->container = $container;
    }
    public function onKernelException(GetResponseForExceptionEvent $event)
    {
        // We get the exception object from the received event
        $exception = $event->getException();
        $response = new Response($this->container->get('templating')->renderResponse('UserBundle:Exception:error403.html.twig',
            array('exception'=>$exception->getMessage())));

        $event->setResponse($response);
    }

}

IN your services.yml

services:
        core.exceptlistener:
            class:  UserBundle\Listener\ExceptionListener
            arguments: ['@service_container', '@templating']
            tags:
                { name: kernel.event_listener, event: kernel.exception, method: onKernelException }

Upvotes: 1

Related Questions